package com.richapp.launcher.net.remote;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jack.netty.log.LoggerManager;
import com.jack.netty.tcp.client.TLVClientListener;
import com.jack.util.date.DateUtil;
import com.jack.util.math.DoubleUtil;
import com.jack.util.string.StringUtil;
import com.richapp.launcher.busevent.EventUnbindBox;
import com.richapp.launcher.control.MoveControl;
import com.richapp.launcher.control.PageControl;
import com.richapp.launcher.control.VolumeControl;
import com.richapp.launcher.database.infrared.dao.BrandDao;
import com.richapp.launcher.database.infrared.dao.BrandModelButtonDao;
import com.richapp.launcher.database.infrared.dao.BrandModelDao;
import com.richapp.launcher.database.infrared.mode.Brand;
import com.richapp.launcher.database.infrared.mode.BrandModel;
import com.richapp.launcher.database.system.dao.ActionInfraredModelDao;
import com.richapp.launcher.database.system.dao.ActionModelDao;
import com.richapp.launcher.database.system.dao.BoxLoginDao;
import com.richapp.launcher.database.system.dao.BoxModelDao;
import com.richapp.launcher.database.system.dao.BoxPhoneDao;
import com.richapp.launcher.database.system.dao.ConditionSensorModelDao;
import com.richapp.launcher.database.system.dao.ConditionStatusModelDao;
import com.richapp.launcher.database.system.dao.ConditionTimeModelDao;
import com.richapp.launcher.database.system.dao.DeviceDayPowerConsumptionDao;
import com.richapp.launcher.database.system.dao.DeviceModelDao;
import com.richapp.launcher.database.system.dao.DeviceModelHistoryDao;
import com.richapp.launcher.database.system.dao.DeviceMonthPowerConsumptionDao;
import com.richapp.launcher.database.system.dao.RoomModelDao;
import com.richapp.launcher.database.system.dao.SceneModelDao;
import com.richapp.launcher.database.system.dao.SystemValueModelDao;
import com.richapp.launcher.database.system.dao.UserLoginDao;
import com.richapp.launcher.database.system.dao.UserMachineButtonDao;
import com.richapp.launcher.database.system.dao.UserMachineDao;
import com.richapp.launcher.database.system.dao.UserModelDao;
import com.richapp.launcher.database.system.mode.ActionInfraredModel;
import com.richapp.launcher.database.system.mode.ActionModel;
import com.richapp.launcher.database.system.mode.BoxLisence;
import com.richapp.launcher.database.system.mode.BoxLogin;
import com.richapp.launcher.database.system.mode.BoxModel;
import com.richapp.launcher.database.system.mode.ConditionSensorModel;
import com.richapp.launcher.database.system.mode.ConditionStatusModel;
import com.richapp.launcher.database.system.mode.ConditionTimeModel;
import com.richapp.launcher.database.system.mode.DeviceModel;
import com.richapp.launcher.database.system.mode.RoomModel;
import com.richapp.launcher.database.system.mode.SceneModel;
import com.richapp.launcher.database.system.mode.SystemValueModel;
import com.richapp.launcher.database.system.mode.UserMachine;
import com.richapp.launcher.database.system.mode.UserMachineButton;
import com.richapp.launcher.database.system.mode.UserModel;
import com.richapp.launcher.net.MessageIdManager;
import com.richapp.launcher.net.box.tcp.client.BoxClient;
import com.richapp.launcher.net.box.tcp.client.BoxClientManager;
import com.richapp.launcher.net.box.tcp.server.BoxServer;
import com.richapp.launcher.net.message.MsgConstant;
import com.richapp.launcher.net.mobile.message.DeviceStatusReply;
import com.richapp.launcher.net.mobile.server.UserServer;
import com.richapp.launcher.receiver.LauncherMessageReceiver;
import com.richapp.launcher.scene.SceneServer;
import com.richapp.launcher.serialport.gateway.GatewaytConstant;
import com.richapp.launcher.serialport.gateway.command.AddCmd;
import com.richapp.launcher.serialport.gateway.command.ControlDeviceCmd;
import com.richapp.launcher.serialport.gateway.command.InfraredControlCmd;
import com.richapp.launcher.serialport.gateway.command.QueryCmd;
import com.richapp.launcher.serialport.gateway.command.RestCmd;
import com.richapp.launcher.serialport.infrared.InfraredServer;
import com.richapp.launcher.serialport.infrared.message.ControlMessage;
import com.richapp.launcher.utils.Constants;
import com.richapp.launcher.utils.DeanTLVClient;
import com.richapp.launcher.utils.JackMd5;
import com.richapp.launcher.utils.Tools;
import com.richapp.net.util.HexTool;
import com.tasogo.RemoteLib.Remote_obj;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import de.greenrobot.event.EventBus;


public class RemoteClient extends DeanTLVClient implements TLVClientListener {

    private Context context;
    /**
     * 服务器通讯server
     */
    private static RemoteClient remoteClient;
    private String TAG = RemoteClient.class.getName();
    private String remoteServerIp = "120.26.199.77";//家商联
    private int remoteServerPort = 53652;
    private boolean loginFlag = false;
    private SceneServer sceneServer = null;

    private DeviceModelDao deviceModelDao = null;
    private DeviceModelHistoryDao deviceModelHistoryDao = null;
    private DeviceDayPowerConsumptionDao deviceDayPowerConsumptionDao;
    private DeviceMonthPowerConsumptionDao deviceMonthPowerConsumptionDao;
    private SystemValueModelDao systemValueModelDao = null;
    private SceneModelDao sceneModelDao = null;
    private UserMachineDao userMachineDao = null;
    private BoxModelDao boxModelDao = null;
    private RoomModelDao roomModelDao = null;
    private UserModelDao userModelDao = null;
    private ConditionTimeModelDao conditionTimeModelDao = null;
    private ConditionStatusModelDao conditionStatusModelDao = null;
    private ConditionSensorModelDao conditionSensorModelDao = null;
    private ActionModelDao actionModelDao = null;
    private ActionInfraredModelDao actionInfraredModelDao = null;
    private BrandDao brandDao = null;
    private BrandModelDao brandModelDao = null;
    private BrandModelButtonDao brandModelButtonDao = null;
    private UserMachineButtonDao userMachineButtonDao = null;
    private BoxLoginDao boxLoginDao = null;
    private UserLoginDao userLoginDao = null;
    private BoxPhoneDao boxPhoneDao;

    private RemoteClient() {
        setIp(remoteServerIp);
        setPort(remoteServerPort);
        setTlvClientListener(this);
//        setRestartFlag(false);
        setRestartTime(10);
        setClientName("机顶盒->服务器");
    }

    public static RemoteClient getInstance() {
        if (remoteClient == null) {
            remoteClient = new RemoteClient();
        }
        return remoteClient;
    }

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
        boxModelDao = new BoxModelDao(context);
        roomModelDao = new RoomModelDao(context);
        userModelDao = new UserModelDao(context);
        deviceModelDao = new DeviceModelDao(context);
        deviceModelHistoryDao = new DeviceModelHistoryDao(context);
        deviceDayPowerConsumptionDao = new DeviceDayPowerConsumptionDao(context);
        deviceMonthPowerConsumptionDao = new DeviceMonthPowerConsumptionDao(context);
        systemValueModelDao = new SystemValueModelDao(context);
        sceneModelDao = new SceneModelDao(context);
        userMachineDao = new UserMachineDao(context);
        conditionTimeModelDao = new ConditionTimeModelDao(context);
        conditionStatusModelDao = new ConditionStatusModelDao(context);
        conditionSensorModelDao = new ConditionSensorModelDao(context);
        actionModelDao = new ActionModelDao(context);
        actionInfraredModelDao = new ActionInfraredModelDao(context);
        brandDao = new BrandDao(context);
        brandModelDao = new BrandModelDao(context);
        brandModelButtonDao = new BrandModelButtonDao(context);
        userMachineButtonDao = new UserMachineButtonDao(context);
        boxLoginDao = new BoxLoginDao(context);
        userLoginDao = new UserLoginDao(context);
        boxPhoneDao = new BoxPhoneDao(context);
    }

    public void remoteLogin() {

        BoxModel ctBox = boxModelDao.getCurrentBox();

        if (!loginFlag) {

            RemoteValidateMessage rvm = new RemoteValidateMessage();
            rvm.setCurrentBoxCpuId(ctBox.getBoxCpuId());
            rvm.setBoxModel(ctBox);
            rvm.setSystemValueList(systemValueModelDao.getList());
            if (ctBox.getUserName() != null && !"".equals(ctBox.getUserName().trim())) {
                //发送验证信息
                rvm.setRoomList(roomModelDao.getRoomList());
                rvm.setUserModel(userModelDao.getByName(ctBox.getUserName()));
                rvm.setDeviceList(deviceModelDao.getDeviceListByBoxCpuId(boxModelDao.getCurrentBox().getBoxCpuId()));
                rvm.setSceneList(sceneModelDao.getList());
                rvm.setMachineList(userMachineDao.getListDetail(boxModelDao.getCurrentBox().getUserName()));
                rvm.setBoxLisence(BoxLisence.getInstance());
            }
            sendMessage(JSON.toJSONString(rvm));
        }
    }

    public void remoteloginRepley(JSONObject replayObj) {
        Log.d(TAG, "自动登录reply");
        boxModelDao.delAll();
        JSONObject boxObj = replayObj.getJSONObject("boxInfo");
        JSONObject userObj = replayObj.getJSONObject("userInfo");
        JSONArray boxArr = replayObj.getJSONArray("boxList");
        JSONArray roomArr = replayObj.getJSONArray("roomList");
        JSONArray deviceArr = replayObj.getJSONArray("deviceList");
        JSONArray systemValueArr = replayObj.getJSONArray("systemValueList");
        JSONArray sceneArr = replayObj.getJSONArray("sceneList");
        JSONArray machineArr = replayObj.getJSONArray("userMachineList");

        BoxModel currentBox = boxModelDao.getCurrentBox();
        //检查是否是自己的反馈
        String boxcpuId = boxObj.getString("boxCpuId");
        if (!currentBox.getBoxCpuId().equals(boxcpuId)) {
            Log.d(TAG, "不是自己的反馈");
            return;
        }

        //判断绑定
        if (boxObj.getString("userName") == null) {
            return;
        } else {
            //存储用户
            UserModel userModel = userModelDao.getUserFirst();
            if (userModel != null) {
                userModelDao.del(userModel);
            }
            userModel = new UserModel();
            userModel.setUserName(boxObj.getString("userName"));
            userModel.setEmail(userObj.getString("email"));
            userModel.setIdCard(userObj.getString("idCard"));
            userModel.setIp(currentBox.getBoxInsideIp());
            userModel.setLogo(userObj.getString("logo"));
            userModel.setNickName(userObj.getString("nickName"));
            userModel.setPhone(userObj.getString("phone"));
            userModel.setPassword(userObj.getString("password"));
            userModel.setCameraLoginName(userObj.getString("cameraLoginName"));
            userModel.setCameraPassword(userObj.getString("cameraPassword"));
            userModelDao.add(userModel);

            //存储box信息
            currentBox.setBoxName(boxObj.getString("boxName"));
            currentBox.setUserName(boxObj.getString("userName"));
            boxModelDao.add(currentBox);
            currentBox = boxModelDao.getCurrentBox();

            //更新房间用户名
            roomModelDao.updateAllUnbindRoomUserInfo(boxObj.getString("userName"));
        }

        //更新box列表
        JSONObject boxArrObj;
        BoxModel boxModel;
        if (boxArr != null) {
            for (int i = 0; i < boxArr.size(); i++) {
                boxArrObj = boxArr.getJSONObject(i);
                if (!boxArrObj.getString("boxCpuId").equals(currentBox.getBoxCpuId())) {
                    boxModel = boxModelDao.getBoxByCpuId(boxArrObj.getString("boxCpuId"));
                    if (boxModel == null) {
                        boxModel = new BoxModel();
                        boxModel.setUserName(boxArrObj.getString("userName"));
                        boxModel.setBoxName(boxArrObj.getString("boxName"));
                        boxModel.setBoxCpuId(boxArrObj.getString("boxCpuId"));
                        boxModel.setBoxInsideIp(boxArrObj.getString("boxInsideIp"));
                        boxModel.setStatus(boxArrObj.getString("status"));
                        boxModel.setLastHandelTime(boxArrObj.getString("lastHandelTime"));
                        boxModel.setDistributorId(boxArrObj.getString("distributorId"));
                        boxModelDao.add(boxModel);
                    } else {
                        boxModel.setUserName(boxArrObj.getString("userName"));
                        boxModel.setBoxName(boxArrObj.getString("boxName"));
                        boxModel.setBoxInsideIp(boxArrObj.getString("boxInsideIp"));
                        boxModel.setStatus(boxArrObj.getString("status"));
                        boxModel.setLastHandelTime(boxArrObj.getString("lastHandelTime"));
                        boxModel.setDistributorId(boxArrObj.getString("distributorId"));
                        boxModelDao.add(boxModel);
                    }
                }
            }
        }


        //更新房间信息
        JSONObject roomArrObj;
        RoomModel roomModel;
        for (int i = 0; i < roomArr.size(); i++) {
            roomArrObj = roomArr.getJSONObject(i);
            roomModel = roomModelDao.getByName(roomArrObj.getString("roomName"));
            if (roomModel == null) {
                roomModel = new RoomModel();
                roomModel.setUserName(roomArrObj.getString("userName"));
                roomModel.setRoomName(roomArrObj.getString("roomName"));
                roomModelDao.add(roomModel);
            }
        }

        //更新设备信息
        JSONObject deviceArrObj;
        DeviceModel deviceModel;
        if (deviceArr.size()>0){
//            deviceModelDao.delAll();
            Log.v(TAG,deviceArr.size()+"--------服务端设备数------------");
        }
        for (int i = 0; i < deviceArr.size(); i++) {
            deviceArrObj = deviceArr.getJSONObject(i);

            String sboxCpuId = deviceArrObj.getString("boxCpuId");
            String sdeviceId = deviceArrObj.getString("deviceId");
            String sdeviceNumber = deviceArrObj.getString("deviceNumber");
            String sway = deviceArrObj.getString("way");
            deviceModel = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(sboxCpuId, sdeviceId, sdeviceNumber, sway);
            if (deviceModel == null) {
                deviceModel = new DeviceModel();
                deviceModel.setBoxCpuId(sboxCpuId);
                deviceModel.setDeviceId(sdeviceId);
                deviceModel.setDeviceNumber(sdeviceNumber);
                deviceModel.setWay(sway);
            }
            deviceModel.setMonitorState(deviceArrObj.getString("monitorState"));
            deviceModel.setLockedStatus(deviceArrObj.getString("lockedStatus"));
            deviceModel.setSignal(deviceArrObj.getString("signal"));
            deviceModel.setIfAnyone(deviceArrObj.getString("ifAnyone"));
            deviceModel.setCheckTime(deviceArrObj.getInteger("checkTime"));
            deviceModel.setOnlineStatus(deviceArrObj.getString("onlineStatus"));
            deviceModel.setAlarmFlag(deviceArrObj.getString("alarmFlag"));
            deviceModel.setCarbonDioxide(deviceArrObj.getString("carbonDioxide"));
            deviceModel.setTemperature(DoubleUtil.isDouble(deviceArrObj.getString("temperature")) ? deviceArrObj.getDouble("temperature") : null);
            deviceModel.setVersion(deviceArrObj.getString("version"));
            deviceModel.setSunLight(deviceArrObj.getInteger("sunLight"));
            deviceModel.setDeviceName(deviceArrObj.getString("deviceName"));
            deviceModel.setLastAlarmTime(deviceArrObj.getLong("lastAlarmTime"));
            deviceModel.setRoomName(deviceArrObj.getString("roomName"));
            deviceModel.setPower(deviceArrObj.getString("power"));
            deviceModel.setLockTongueStatus(deviceArrObj.getString("lockTongueStatus"));
            deviceModel.setAriQuality(deviceArrObj.getInteger("ariQuality"));
            deviceModel.setLockKeyStatus(deviceArrObj.getString("lockKeyStatus"));
            deviceModel.setDeviceStatus(deviceArrObj.getString("deviceStatus"));
            deviceModel.setHumidity(deviceArrObj.getInteger("humidity"));
            deviceModel.setPm25(deviceArrObj.getInteger("pm25"));
            deviceModel.setBusyStatus(deviceArrObj.getString("busyStatus"));
            deviceModel.setPowerStatus(deviceArrObj.getString("powerStatus"));
            deviceModelDao.add(deviceModel);
        }

        //systemValueArr
        if (systemValueArr != null) {
            JSONObject systemValueObj = null;
            for (int i = 0; i < systemValueArr.size(); i++) {
                systemValueObj = systemValueArr.getJSONObject(i);
                if (systemValueObj != null) {
                    String settingName = systemValueObj.getString("settingName");
                    String settingValue = systemValueObj.getString("settingValue");
                    String boxCpuId = systemValueObj.getString("boxCpuId");
                    if (StringUtil.isNullOrEmpty(settingName, settingValue, boxCpuId)) {
                        if (boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)) {
                            SystemValueModel systemValueModel = systemValueModelDao.getByName(boxCpuId, settingName);
                            if (systemValueModel == null) {
                                systemValueModel = new SystemValueModel();
                                systemValueModel.setBoxCpuId(boxCpuId);
                                systemValueModel.setName(settingName);
                            }
                            systemValueModel.setValue(settingValue);
                            systemValueModelDao.add(systemValueModel);
                        }
                    }
                }
            }
        }

        //清空家电动作表
        ActionInfraredModel actionInfraredModelOne = actionInfraredModelDao.getFirst();
        if (actionInfraredModelOne != null) {
            actionInfraredModelDao.delAll();
        }

        //sceneArr
        if (sceneArr != null) {
            conditionStatusModelDao.delAll();//清空原有状态条件
            actionModelDao.delAll();//清空原来的动作数据
            conditionSensorModelDao.delAll();//清空原来的传感条件
            conditionTimeModelDao.delAll();//清空原来的时间条件
            JSONObject sceneObj = null;
            for (int i = 0; i < sceneArr.size(); i++) {
                sceneObj = sceneArr.getJSONObject(i);
                if (sceneObj != null) {
                    SceneModel sceneModel = sceneModelDao.get(sceneObj.getString("sceneName"));
                    if (sceneModel == null) {
                        sceneModel = new SceneModel();
                        sceneModel.setSceneName(sceneObj.getString("sceneName"));
                    }
                    sceneModel.setStatusCycleFlag(sceneObj.getString("statusCycleFlag"));
                    sceneModel.setBoxCpuId(sceneObj.getString("boxCpuId"));
                    sceneModel.setCreateTime(sceneObj.getLong("createTime"));
                    sceneModel.setCheckModel(sceneObj.getString("checkModel"));
                    sceneModel.setSceneType(sceneObj.getInteger("sceneType"));
                    sceneModel.setIconName(sceneObj.getString("iconName"));
                    sceneModel.setOpenFlag(sceneObj.getString("openFlag"));
                    sceneModel.setDeviceNumber(sceneObj.getString("deviceNumber"));
                    sceneModel.setSceneBindKey(sceneObj.getString("sceneBindKey"));
                    sceneModelDao.add(sceneModel);


                    //2.添加条件
                    ////A.添加时间条件
                    JSONArray timeConditionList = sceneObj.getJSONArray("timeModelList");
                    if (timeConditionList != null) {
                        if (timeConditionList.size() > 1) {
                            Log.e(TAG, "时间条件集合数据大于1");
                            return;
                        }

                        if (timeConditionList.size() > 0) {
                            JSONObject timeConditionObj = timeConditionList.getJSONObject(0);
                            ConditionTimeModel conditionTimeModel = new ConditionTimeModel();
                            conditionTimeModel.setSceneName(sceneObj.getString("sceneName"));
                            conditionTimeModel.setConditionType(0);
                            switch (timeConditionObj.getInteger("conditionSubType")) {
                                case 0://延时
                                    conditionTimeModel.setDelayStartTime(System.currentTimeMillis());
                                    conditionTimeModel.setDelayDelayTime(timeConditionObj.getLong("delayDelayTime"));
                                    conditionTimeModel.setConditionSubType(0);
                                    break;
                                case 1://时效
                                    conditionTimeModel.setAgingStartTime(timeConditionObj.getLong("agingStartTime"));
                                    conditionTimeModel.setAgingStopTime(timeConditionObj.getLong("agingStopTime"));
                                    conditionTimeModel.setConditionSubType(1);
                                    break;
                                case 2://定时
                                    conditionTimeModel.setConditionSubType(2);
                                    conditionTimeModel.setDimingModelType(timeConditionObj.getInteger("dimingModelType"));
                                    conditionTimeModel.setHours(timeConditionObj.getInteger("hours"));
                                    conditionTimeModel.setMinutes(timeConditionObj.getInteger("minutes"));
                                    conditionTimeModel.setSeconds(timeConditionObj.getInteger("seconds"));
                                    switch (conditionTimeModel.getDimingModelType()) {
                                        case 0://每天
                                            break;
                                        case 1://每周
                                            conditionTimeModel.setWeekDays(timeConditionObj.getString("timingList"));
                                            break;
                                        case 2://每月
                                            conditionTimeModel.setMonthDays(timeConditionObj.getString("timingList"));
                                            break;
                                        default:
                                            Log.e(TAG, "未定义的定时模式");
                                            break;
                                    }
                                    break;
                                default:
                                    Log.e(TAG, "未定义的时间类型");
                                    break;
                            }
                            conditionTimeModelDao.add(conditionTimeModel);
                        }
                    }



                    //B.添加状态条件
                    JSONArray conditionStateList = sceneObj.getJSONArray("statusModelList");
                    if (conditionStateList != null) {
                        Iterator iterator = conditionStateList.iterator();
                        JSONObject conditionStateObj = null;
                        ConditionStatusModel conditionStatusModel = null;
                        while (iterator.hasNext()) {
                            conditionStatusModel = new ConditionStatusModel();
                            conditionStateObj = (JSONObject) iterator.next();
                            conditionStatusModel.setConditionType(conditionStateObj.getInteger("conditionType"));
                            conditionStatusModel.setBoxCpuId(conditionStateObj.getString("boxCpuId"));
                            conditionStatusModel.setSceneName(conditionStateObj.getString("sceneName"));
                            conditionStatusModel.setDeviceId(conditionStateObj.getString("deviceId"));
                            conditionStatusModel.setDeviceNumber(conditionStateObj.getString("deviceNumber"));
                            conditionStatusModel.setWay(conditionStateObj.getString("way") == null ? "01" : conditionStateObj.getString("way"));
                            conditionStatusModel.setDeviceName(conditionStateObj.getString("deviceName"));
                            conditionStatusModel.setIfAnyone(conditionStateObj.getString("ifAnyone"));
                            conditionStatusModel.setDimmingValue(conditionStateObj.getString("dimmingValue"));
                            conditionStatusModel.setConditionSubType(conditionStateObj.getInteger("conditionSubType"));
                            conditionStatusModel.setDeviceStatus(conditionStateObj.getString("deviceStatus"));
                            conditionStatusModel.setConditionCycleFlag(conditionStateObj.getString("conditionCycleFlag"));

                            if("0D".equals(conditionStateObj.getString("deviceId"))){
                                if("00".equals(conditionStateObj.getString("deviceStatus"))){
                                    conditionStatusModel.setConditionSubType(1);
                                }else if ("01".equals(conditionStateObj.getString("deviceStatus"))){
                                    conditionStatusModel.setConditionSubType(0);
                                }
                            }else if ("17".equals(conditionStateObj.getString("deviceId"))){
                                if("C4".equals(conditionStateObj.getString("deviceStatus"))){
                                    conditionStatusModel.setConditionSubType(1);
                                }else if ("C0".equals(conditionStateObj.getString("deviceStatus"))){
                                    conditionStatusModel.setConditionSubType(0);
                                }

                            }else if ("0E".equals(conditionStateObj.getString("deviceId"))){
                                if("77".equals(conditionStateObj.getString("deviceStatus"))){
                                    conditionStatusModel.setConditionSubType(1);
                                }else if ("75".equals(conditionStateObj.getString("deviceStatus"))){
                                    conditionStatusModel.setConditionSubType(1);
                                }else if ("71".equals(conditionStateObj.getString("deviceStatus"))){
                                    conditionStatusModel.setConditionSubType(0);
                                }
                            }else {
                                if("00".equals(conditionStateObj.getString("deviceStatus"))){
                                    conditionStatusModel.setConditionSubType(1);
                                }else if ("FF".equals(conditionStateObj.getString("deviceStatus"))){
                                    conditionStatusModel.setConditionSubType(0);
                                }
                            }
                            switch (conditionStatusModel.getConditionSubType()) {
                                case 2: //调度状态
                                    conditionStatusModel.setDimmingValue(conditionStateObj.getString("deviceStatus"));
                                    break;
                                default:
                                    break;
                            }
                            conditionStatusModelDao.add(conditionStatusModel);
                        }
                    }

                    ////C.添加传感条件
                    JSONArray conditionSensingList = sceneObj.getJSONArray("sensorModelList");
                    if (conditionSensingList != null) {
                        Iterator iterator1 = conditionSensingList.iterator();
                        JSONObject conditionSensorObj = null;
                        ConditionSensorModel conditionSensorModel = null;
                        while (iterator1.hasNext()) {
                            conditionSensorObj = (JSONObject) iterator1.next();
                            conditionSensorModel = new ConditionSensorModel();
                            conditionSensorModel.setSceneName(sceneObj.getString("sceneName"));
                            conditionSensorModel.setConditionType(1);
                            conditionSensorModel.setConditionSubType(conditionSensorObj.getInteger("conditionSubType"));
                            conditionSensorModel.setBoxCpuId(conditionSensorObj.getString("boxCpuId"));
                            conditionSensorModel.setDeviceId(conditionSensorObj.getString("deviceId"));
                            conditionSensorModel.setDeviceNumber(conditionSensorObj.getString("deviceNumber"));
                            conditionSensorModel.setWay(conditionSensorObj.getString("way") == null ? "01" : conditionSensorObj.getString("way"));
                            conditionSensorModel.setDeviceName(conditionSensorObj.getString("deviceName"));
                            conditionSensorModel.setConditionCheckModel(conditionSensorObj.getString("conditionCheckModel"));
                            conditionSensorModel.setConditionCycleFlag(conditionSensorObj.getString("conditionCycleFlag"));
                            switch (conditionSensorModel.getConditionSubType()) {
                                case 0: //二氧化碳
                                    conditionSensorModel.setCheckCO2Value(conditionSensorObj.getInteger("checkCO2Value"));
                                    break;
                                case 1: //空气质量
                                    conditionSensorModel.setCheckAirValue(conditionSensorObj.getString("checkAirValue"));
                                    break;
                                case 2: //PM2.5
                                    conditionSensorModel.setCheckPM25Value(conditionSensorObj.getInteger("checkPM25Value"));
                                    break;
                                case 3: //光照
                                    conditionSensorModel.setCheckLightValue(conditionSensorObj.getInteger("checkLightValue"));
                                    break;
                                case 4: //温湿度

                                    if(conditionSensorObj.getInteger("checkTemperatureValue")==-1314){
                                        conditionSensorModel.setCheckHumidityValue(conditionSensorObj.getInteger("checkHumidityValue"));
                                    }else {
                                        conditionSensorModel.setCheckTemperatureValue(conditionSensorObj.getInteger("checkTemperatureValue"));
                                    }


//                                    String[] values = conditionSensorObj.getString("checkValue").split("\\|");
//                                    if (!"null".equals(values[0])) {
//                                        conditionSensorModel.setCheckTemperatureValue(Integer.parseInt(values[0]));
//                                    } else {
//                                        conditionSensorModel.setCheckTemperatureValue(-1);
//                                    }
//
//                                    if (!"null".equals(values[1])) {
//                                        conditionSensorModel.setCheckHumidityValue(Integer.parseInt(values[1]));
//                                    } else {
//                                        conditionSensorModel.setCheckHumidityValue(-1);
//                                    }


                                    break;
                                case 5: //风雨传感器

                                    break;
                                case 6: //报警类设备
                                    conditionSensorModel.setCheckAlarmValue(conditionSensorObj.getString("checkAlarmValue"));
                                    break;
                                default:
                                    Log.e(TAG, "未定义的传感条件类型");
                                    break;
                            }
                            conditionSensorModelDao.add(conditionSensorModel);
                        }
                    }


                    //3.添加动作
                    JSONArray actionList = sceneObj.getJSONArray("actionModelList");
                    if (actionList != null) {
                        Iterator iterator2 = actionList.iterator();
                        ActionModel actionModel = null;
                        JSONObject actionObj = null;
                        while (iterator2.hasNext()) {
                            actionObj = (JSONObject) iterator2.next();
                            actionModel = new ActionModel();
                            actionModel.setSceneName(sceneObj.getString("sceneName"));
                            actionModel.setActionType(actionObj.getInteger("actionType"));
                            actionModel.setBoxCpuId(actionObj.getString("boxCpuId"));
                            actionModel.setDeviceId(actionObj.getString("deviceId"));
                            actionModel.setDeviceNumber(actionObj.getString("deviceNumber"));
                            actionModel.setWay(actionObj.getString("way") == null ? "01" : actionObj.getString("way"));
                            actionModel.setDeviceName(actionObj.getString("deviceName"));
                            actionModel.setDelayActionTime(actionObj.getInteger("delayActionTime"));
                            actionModel.setOrderNumber(Integer.parseInt(actionObj.getString("orderNumber")));
                            switch (actionModel.getActionType()) {
                                case 2:
                                    actionModel.setDimmingValue(actionObj.getString("dimmingValue"));
                                    break;
                                default:
                                    break;
                            }

                            actionModelDao.add(actionModel);
                        }
                    }

                    //添加家电动作
                    JSONArray actionInfraredList = null;
                    actionInfraredList = sceneObj.getJSONArray("actionInfraredModelList");
                    Log.v(TAG, "动作数据大小：" + actionInfraredList.size());
                    if (actionInfraredList != null) {
                        Iterator iterator3 = actionInfraredList.iterator();
                        JSONObject actionInfraredObj = null;
                        ActionInfraredModel actionInfraredModel = null;
                        for (int j = 0; j < actionInfraredList.size(); j++) {
                            actionInfraredObj = (JSONObject) iterator3.next();
                            Log.v(TAG, "动作数据大小：" + actionInfraredObj.toString());

                            actionInfraredModel = new ActionInfraredModel();
                            actionInfraredModel.setSceneName(sceneObj.getString("sceneName"));
                            actionInfraredModel.setActionType(actionInfraredObj.getInteger("actionType"));
                            actionInfraredModel.setMachineName(actionInfraredObj.getString("machineName"));
                            actionInfraredModel.setButtonId(actionInfraredObj.getInteger("buttonId"));
                            actionInfraredModel.setButtonName(actionInfraredObj.getString("buttonName"));
                            actionInfraredModel.setDelayActionTime(actionInfraredObj.getInteger("delayActionTime"));
                            actionInfraredModel.setOrderNumber(Integer.parseInt(actionInfraredObj.getString("orderNumber")) );
                            actionInfraredModelDao.add(actionInfraredModel);

                        }
                    }


                }
            }
        }

        //machineArr
        if (machineArr != null) {
            if (machineArr.size() > 0) {
                JSONObject machineObj;
                UserMachine userMachine;
                UserMachineButton userMachineButton;
                for (int i = 0; i < machineArr.size(); i++) {
                    machineObj = machineArr.getJSONObject(i);
                    if (machineObj != null) {
                        userMachine = userMachineDao.get(machineObj.getString("userName"), machineObj.getString("machineName"));
                        if (userMachine == null) {
                            userMachine = new UserMachine();
                            userMachine.setUserName(machineObj.getString("userName"));
                            userMachine.setMachineName(machineObj.getString("machineName"));
                        }
                        userMachine.setBoxCpuId(machineObj.getString("boxCpuId"));
                        userMachine.setAddType(machineObj.getInteger("addType"));
                        userMachine.setBrandModelId(machineObj.getInteger("brandModelId"));
                        userMachine.setRoomName(machineObj.getString("roomName"));
                        userMachine.setStatus(machineObj.getString("status"));

                        userMachine.setBindBoxCpuId(machineObj.getString("bindBoxCpuId"));
                        userMachine.setBindDeviceNumber(machineObj.getString("bindDeviceNumber"));
                        userMachine.setBindDeviceId(machineObj.getString("bindDeviceId"));
                        userMachine.setBindWay(machineObj.getString("bindWay"));
                        userMachine.setMachineTypeId(machineObj.getInteger("machineTypeId"));
                        userMachineDao.add(userMachine);

                        JSONArray btnArr = machineObj.getJSONArray("userMachineButtonList");
                        JSONObject btnObj;
                        if (btnArr != null) {
                            for (int k = 0; k < btnArr.size(); k++) {
                                btnObj = btnArr.getJSONObject(k);
                                if (btnObj != null) {
                                    userMachineButton = userMachineButtonDao.get(machineObj.getString("machineName"), btnObj.getInteger("buttonId"));
                                    if (userMachineButton == null) {
                                        userMachineButton = new UserMachineButton();
                                        userMachineButton.setMachineName(machineObj.getString("machineName"));
                                        userMachineButton.setButtonId(btnObj.getInteger("buttonId"));
                                    }
                                    userMachineButton.setButtonName(btnObj.getString("buttonName"));
                                    userMachineButton.setCode(btnObj.getString("code"));
                                    userMachineButton.setStudyFlag(btnObj.getString("studyFlag"));
                                    userMachineButtonDao.add(userMachineButton);
                                }
                            }
                        }
                    }
                }
            }
        }

        System.out.println("replay end");

        UserServer.getInstance().userInfoUpdate();

        setLoginFlag(true);

        //数据同步完成时加载情景
        sceneServer = sceneServer.getInstance();
        sceneServer.setContext(SceneServer.getInstance().getContext());
        sceneServer.setSceneOpenFlag(true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                SceneServer.getInstance().loadSceneList();
                Log.v(TAG,"------数据同步完成时情景加载完成--------");

            }
        }).start();


    }

    public boolean isLoginFlag() {
        return loginFlag;
    }

    public void setLoginFlag(boolean loginFlag) {
        this.loginFlag = loginFlag;
    }

    //type = 2 盲添结果转发处理
    public void doBoxMindAdd(String serverId, JSONObject jsonObject) {

        JSONArray deviceList = jsonObject.getJSONArray("deviceList");

        //如果deviceList不为空的话，说明是反馈添加后的消息
        if (deviceList != null) {
            if (deviceList.size() > 0) {
                JSONObject deviceObj;
                DeviceModel currentDeviceModel;
                for (int i = 0; i < deviceList.size(); i++) {
                    deviceObj = deviceList.getJSONObject(i);
                    currentDeviceModel = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(deviceObj.getString("boxCpuId"), deviceObj.getString("deviceId"), deviceObj.getString("deviceNumber"), deviceObj.getString("way"));
                    if (currentDeviceModel == null) {    //添加
                        currentDeviceModel = new DeviceModel();
                        currentDeviceModel.setAriQuality(deviceObj.getInteger("ariQuality"));
                        currentDeviceModel.setBoxCpuId(deviceObj.getString("boxCpuId"));
                        currentDeviceModel.setBusyStatus(deviceObj.getString("busyStatus"));
                        currentDeviceModel.setCarbonDioxide(deviceObj.getString("carbonDioxide"));
                        currentDeviceModel.setCheckTime(deviceObj.getIntValue("checkTime"));
                        currentDeviceModel.setDeviceId(deviceObj.getString("deviceId"));
                        currentDeviceModel.setDeviceName(deviceObj.getString("deviceName"));
                        currentDeviceModel.setDeviceNumber(deviceObj.getString("deviceNumber"));
                        currentDeviceModel.setWay(deviceObj.getString("way"));
                        currentDeviceModel.setDeviceStatus(deviceObj.getString("deviceStatus"));
                        currentDeviceModel.setHumidity(deviceObj.getInteger("humidity"));
                        currentDeviceModel.setMonitorState(deviceObj.getString("monitorState"));
                        currentDeviceModel.setOnlineStatus(deviceObj.getString("onlineStatus"));
                        currentDeviceModel.setPm25(deviceObj.getInteger("pm25"));
                        currentDeviceModel.setPower(deviceObj.getString("power"));
                        currentDeviceModel.setRoomName(deviceObj.getString("roomName"));
                        currentDeviceModel.setSignal(deviceObj.getString("signal"));
                        currentDeviceModel.setIfAnyone(deviceObj.getString("ifAnyone"));
                        currentDeviceModel.setSunLight(deviceObj.getInteger("sunLight"));
                        currentDeviceModel.setTemperature(deviceObj.getDouble("temperature"));
                        currentDeviceModel.setVersion(deviceObj.getString("version"));
                        currentDeviceModel.setPowerStatus(deviceObj.getString("powerStatus"));
                        deviceModelDao.add(currentDeviceModel);
                    } else {//更新
                        currentDeviceModel.setAriQuality(deviceObj.getInteger("ariQuality"));
                        currentDeviceModel.setBusyStatus(deviceObj.getString("busyStatus"));
                        currentDeviceModel.setCarbonDioxide(deviceObj.getString("carbonDioxide"));
                        currentDeviceModel.setCheckTime(deviceObj.getIntValue("checkTime"));
                        currentDeviceModel.setDeviceName(deviceObj.getString("deviceName"));
                        currentDeviceModel.setDeviceNumber(deviceObj.getString("deviceNumber"));
                        currentDeviceModel.setDeviceStatus(deviceObj.getString("deviceStatus"));
                        currentDeviceModel.setHumidity(deviceObj.getInteger("humidity"));
                        currentDeviceModel.setMonitorState(deviceObj.getString("monitorState"));
                        currentDeviceModel.setOnlineStatus(deviceObj.getString("onlineStatus"));
                        currentDeviceModel.setPm25(deviceObj.getInteger("pm25"));
                        currentDeviceModel.setPower(deviceObj.getString("power"));
                        currentDeviceModel.setRoomName(deviceObj.getString("roomName"));
                        currentDeviceModel.setSignal(deviceObj.getString("signal"));
                        currentDeviceModel.setIfAnyone(deviceObj.getString("ifAnyone"));
                        currentDeviceModel.setSunLight(deviceObj.getInteger("sunLight"));
                        currentDeviceModel.setTemperature(deviceObj.getDouble("temperature"));
                        currentDeviceModel.setVersion(deviceObj.getString("version"));
                        currentDeviceModel.setPowerStatus(deviceObj.getString("powerStatus"));
                        deviceModelDao.add(currentDeviceModel);
                    }
                }

                //当前主机连接的手机端
                UserServer.getInstance().sendAllUsersMessage(jsonObject.toString());
            }
        } else {
            BoxModel currentBox = boxModelDao.getCurrentBox();
            String boxCpuId = jsonObject.getString("boxCpuId");
            if (StringUtil.isNullOrEmpty(boxCpuId)) {
                boxCpuId = jsonObject.getString("currentBoxCpuId");
            }

            if (currentBox.getBoxCpuId().equals(boxCpuId)) {
                AddCmd.getInstance().blindAdd();
            }
//            //添加时间戳
//            if(StringUtil.isNullOrEmpty(jsonObject.getString("lastHandelTime")+"")){
//                currentBox.setLastHandelTime( DateUtil.getDateLong()+"");
//            } else {
//                currentBox.setLastHandelTime(jsonObject.getString("lastHandelTime"));
//            }
//
//            //更新操作时间
//            boxModelDao.add(currentBox);
//
//            Log.v(TAG,"操作时间更新成功------"+jsonObject.getString("lastHandelTime"));

            if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
                jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");

                //发送其他机顶盒
                BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
            }
        }

    }

    //type = 3 打开设备
    public void doOpenDevice(String serverId, JSONObject jsonObject) {

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        String deviceId="";
        String deviceNumber="";
        String way="";
        DeviceModel deviceModel=null;
        if (currentBox.getBoxCpuId().equals(boxCpuId)) {
            deviceId = jsonObject.getString("deviceId");
            deviceNumber = jsonObject.getString("deviceNumber");
            way = jsonObject.getString("way");
            String deviceStatus = jsonObject.getString("deviceStatus");
            if (way == null) {
                way = "00";
            }
            deviceModel = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(boxCpuId, deviceId, deviceNumber, way);

            if (deviceModel != null) {
                deviceModel.setDeviceStatus(deviceStatus);
                if ("04".equals(deviceId)){
                    deviceModel.setProcessValue(0);
                }
                deviceModelDao.add(deviceModel);
            }


            Log.v(TAG, "收到开启消息:" + " 主机:" + boxCpuId + " 设备类型:" + deviceId + " 设备编号:" + deviceNumber + " 设备路数:" + way + "路");
            if (deviceId != null && deviceNumber != null) {
                ControlDeviceCmd.getInstance().openDevice(boxCpuId, deviceId, deviceNumber, way);
            }
        }

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
        if("04".equals(jsonObject.getString("deviceId"))){
            final int time=deviceModel.getCheckTime();
            final String finalBoxCpuId = boxCpuId;
            final String finalDeviceId = deviceId;
            final String finalDeviceNumber = deviceNumber;
            final String finalWay = way;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(time);
                        ControlDeviceCmd.getInstance().stopDevice(finalBoxCpuId, finalDeviceId, finalDeviceNumber, finalWay);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }


    }

    //type = 4 关闭设备消息
    public void doCloseDevice(String serverId, JSONObject jsonObject) {

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        String deviceId="";
        String deviceNumber="";
        String way="";
        DeviceModel deviceModel=null;

        if (currentBox.getBoxCpuId().equals(boxCpuId)) {
             deviceId = jsonObject.getString("deviceId");
             deviceNumber = jsonObject.getString("deviceNumber");
             way = jsonObject.getString("way");
            String deviceStatus = jsonObject.getString("deviceStatus");
            if (way == null) {
                way = "00";
            }
             deviceModel = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(boxCpuId, deviceId, deviceNumber, way);
            if (deviceModel != null) {
                deviceModel.setDeviceStatus(deviceStatus);
                if ("04".equals(deviceId)){
                    deviceModel.setProcessValue(100);
                }
                deviceModelDao.add(deviceModel);
            }

            Log.v(TAG, "收到关闭消息:" + " 主机:" + boxCpuId + " 设备类型:" + deviceId + " 设备编号:" + deviceNumber);
            if (deviceId != null && deviceNumber != null) {
                ControlDeviceCmd.getInstance().closeDevice(boxCpuId, deviceId, deviceNumber, way);
            }
        }

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }

        if("04".equals(jsonObject.getString("deviceId"))){

            final int time=deviceModel.getCheckTime();
            final String finalBoxCpuId = boxCpuId;
            final String finalDeviceId = deviceId;
            final String finalDeviceNumber = deviceNumber;
            final String finalWay = way;
            new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(time);
                            ControlDeviceCmd.getInstance().stopDevice(finalBoxCpuId, finalDeviceId, finalDeviceNumber, finalWay);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

        }
    }

    //type = 5 调度设备调度(调光灯，窗帘)
    public void doDemingDevice(String serverId, JSONObject jsonObject) {

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        if (currentBox.getBoxCpuId().equals(boxCpuId)) {
            String deviceId = jsonObject.getString("deviceId");
            String deviceNumber = jsonObject.getString("deviceNumber");
            String deviceStatus = jsonObject.getString("deviceStatus");
            String way = jsonObject.getString("way");
            if (way == null) {
                way = "00";
            }
            if (deviceId != null && deviceNumber != null) {
                ControlDeviceCmd.getInstance().setDimming(boxCpuId, deviceId, deviceNumber, deviceStatus, way);
            }
        }

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type=6,查询设备
    public void doBoxQueryDevice(String serverId, JSONObject jsonObject) {

        BoxModel currentBox = boxModelDao.getCurrentBox();

        JSONArray deviceObjList = jsonObject.getJSONArray("deviceList");

        if (deviceObjList != null) {
            //不指定查询,只查询本机顶盒设备
            if (deviceObjList == null || deviceObjList.size() < 1) {
                List<DeviceModel> deviceList = deviceModelDao.getDeviceListByBoxCpuId(jsonObject.getString("currentBoxCpuId"));
                if (deviceList == null || deviceList.size() < 1) {
                    return;
                } else {
                    for (DeviceModel dm : deviceList) {
                        QueryCmd.getInstance().query(dm.getBoxCpuId(), dm.getDeviceId(), dm.getDeviceNumber(), dm.getWay());
                    }
                }
            } else { //指定设备查询
                JSONObject deviceObj = null;
                for (int i = 0; i < deviceObjList.size(); i++) {
                    deviceObj = deviceObjList.getJSONObject(i);
                    if (currentBox.getBoxCpuId().equals(deviceObj.getString("boxCpuId"))) {
                        QueryCmd.getInstance().query(deviceObj.getString("boxCpuId"), deviceObj.getString("deviceId"), deviceObj.getString("deviceNumber"), deviceObj.getString("way"));
                    }
                }
            }
        }

        JSONArray list = jsonObject.getJSONArray("list");
        if (list != null) {
            JSONObject deviceObj6 = null;
            for (int i = 0; i < list.size(); i++) {
                deviceObj6 = list.getJSONObject(i);
                DeviceModel dm6 = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(deviceObj6.getString("boxCpuId"), deviceObj6.getString("deviceId"), deviceObj6.getString("deviceNumber"), deviceObj6.getString("way"));
                if (dm6 != null) {
                    dm6.setAriQuality(deviceObj6.getInteger("ariQuality"));
                    dm6.setBusyStatus(deviceObj6.getString("busyStatus"));
                    dm6.setCarbonDioxide(deviceObj6.getString("carbonDioxide"));
                    dm6.setCheckTime(deviceObj6.getIntValue("checkTime"));
                    dm6.setDeviceName(deviceObj6.getString("deviceName"));
                    dm6.setDeviceNumber(deviceObj6.getString("deviceNumber"));
                    dm6.setDeviceStatus(deviceObj6.getString("deviceStatus"));
                    dm6.setHumidity(deviceObj6.getInteger("humidity"));
                    dm6.setMonitorState(deviceObj6.getString("monitorState"));
                    dm6.setOnlineStatus(deviceObj6.getString("onlineStatus"));
                    dm6.setPm25(deviceObj6.getInteger("pm25"));
                    dm6.setPower(deviceObj6.getString("power"));
                    dm6.setRoomName(deviceObj6.getString("roomName"));
                    dm6.setSignal(deviceObj6.getString("signal"));
                    dm6.setIfAnyone(deviceObj6.getString("ifAnyone"));
                    dm6.setSunLight(deviceObj6.getInteger("sunLight"));
                    dm6.setTemperature(deviceObj6.getDouble("temperature"));
                    dm6.setVersion(deviceObj6.getString("version"));
                    deviceModelDao.add(dm6);
                }
            }
        }

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());
    }

    //type = 7 设备绑定房间/添加房间
    public void doDeviceBindRoom(String serverId, JSONObject jsonObject) {
        BoxModel currentBox = boxModelDao.getCurrentBox();
        JSONArray jsonArray = jsonObject.getJSONArray("list");
        RoomModel rm;
        DeviceModel dm;

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject devicesRoom = jsonArray.getJSONObject(i);
            JSONObject roomJsonObject = devicesRoom.getJSONObject("room");
            //创建房间
            rm = roomModelDao.getByName(roomJsonObject.getString("roomName"));
            if (rm == null) {
                rm = new RoomModel();
                rm.setUserName(currentBox.getUserName());
                rm.setRoomName(roomJsonObject.getString("roomName"));
                roomModelDao.add(rm);
                rm = roomModelDao.getByName(rm.getRoomName());
            }

            //更新设备信息
            if (devicesRoom.getString("boxCpuId") != null
                    && devicesRoom.getString("deviceId") != null
                    && devicesRoom.getString("deviceNumber") != null) {
                dm = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(devicesRoom.getString("boxCpuId"), devicesRoom.getString("deviceId"), devicesRoom.getString("deviceNumber"), devicesRoom.getString("way"));
                if (dm != null) {
                    dm.setRoomName(rm.getRoomName());
                    dm.setDeviceName(devicesRoom.getString("deviceName"));
//                   deviceModelDao.del(dm);
                    deviceModelDao.add(dm);
                }
            }
        }
//        //添加时间戳
//        if(StringUtil.isNullOrEmpty(jsonObject.getString("lastHandelTime")+"")){
//            currentBox.setLastHandelTime( DateUtil.getDateLong()+"");
//        } else {
//            currentBox.setLastHandelTime(jsonObject.getString("lastHandelTime"));
//        }
//
//        //更新操作时间
//        boxModelDao.add(currentBox);
//
//        Log.v(TAG,"操作时间更新成功------"+jsonObject.getString("lastHandelTime"));

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type = 8 全开设备
    public void doOpenAllDevices(String serverId, JSONObject jsonObject) {

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        if (currentBox.getBoxCpuId().equals(boxCpuId)) {
            //发送底层指令
            ControlDeviceCmd.getInstance().openAllDevice();

            //变更本地数据
            deviceModelDao.setAllOpen(currentBox.getBoxCpuId());

            //构造同步信息
            DeviceStatusReply dsr = new DeviceStatusReply();
            dsr.setCurrentBoxCpuId(currentBox.getBoxCpuId());
            dsr.setUserName(currentBox.getUserName());
            dsr.setDeviceStatus(deviceModelDao.getOpenCloseAllResult(currentBox.getBoxCpuId()));
            dsr.setHEAD_IS_REPLY("true");

            JSONObject jobj = (JSONObject) JSON.toJSON(dsr);

            //发送所有当前手机
            UserServer.getInstance().sendAllUsersMessage(jobj.toJSONString());

            if ("false".equals(jobj.getString(MsgConstant.HEAD_IS_REPLY))) {
                jobj.put(MsgConstant.HEAD_IS_REPLY, "true");
                //发送其他机顶盒
                BoxServer.getInstance().sendAllBoxMessage(jobj.toJSONString());
            }
        }

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type = 9 全关设备
    public void doCloseAllDevices(String serverId, JSONObject jsonObject) {

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        if (currentBox.getBoxCpuId().equals(boxCpuId)) {
            //发送底层指令
            ControlDeviceCmd.getInstance().closeAllDevice();

            //变更本地数据
            deviceModelDao.setAllClose(currentBox.getBoxCpuId());

            //构造同步信息
            DeviceStatusReply dsr = new DeviceStatusReply();
            dsr.setCurrentBoxCpuId(currentBox.getBoxCpuId());
            dsr.setUserName(currentBox.getUserName());
            dsr.setDeviceStatus(deviceModelDao.getOpenCloseAllResult(currentBox.getBoxCpuId()));
            dsr.setHEAD_IS_REPLY("true");
            JSONObject jobj = (JSONObject) JSON.toJSON(dsr);

            //发送所有当前手机
            UserServer.getInstance().sendAllUsersMessage(jobj.toJSONString());

            if ("false".equals(jobj.getString(MsgConstant.HEAD_IS_REPLY))) {
                jobj.put(MsgConstant.HEAD_IS_REPLY, "true");
                //发送其他机顶盒
                BoxServer.getInstance().sendAllBoxMessage(jobj.toJSONString());
            }
        }

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type = 10 添加一类设备
    public void doAddOneDevice(String serverId, JSONObject jsonObject) {

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        if (currentBox.getBoxCpuId().equals(boxCpuId)) {
            AddCmd.getInstance().addOneDevice();
        }
        //添加时间戳
        if (StringUtil.isNullOrEmpty(jsonObject.getString("lastHandelTime") + "")) {
            currentBox.setLastHandelTime(DateUtil.getDateLong() + "");
        } else {
            currentBox.setLastHandelTime(jsonObject.getString("lastHandelTime"));
        }

        //更新操作时间
        boxModelDao.add(currentBox);

        Log.v(TAG, "操作时间更新成功------" + jsonObject.getString("lastHandelTime"));
        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type = 13 ,根据主机，类型，编号删除设备
    public void doDeleteDevice(String serverId, JSONObject jsonObject) {
        BoxModel currentBox = boxModelDao.getCurrentBox();
        List<DeviceModel> dmList;
        JSONArray jsonArray1 = jsonObject.getJSONArray("list");
        JSONObject object = null;
        for (int i = 0; i < jsonArray1.size(); i++) {
            object = jsonArray1.getJSONObject(i);
            if ("1C".equals(object.getString("deviceId"))){
                dmList = deviceModelDao.getByCpuIdDeviceIdDeviceNumberWay(object.getString("boxCpuId"),object.getString("deviceId"), object.getString("deviceNumber"),"01");
            }else {
                dmList = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(object.getString("boxCpuId"),object.getString("deviceId"), object.getString("deviceNumber"));
            }
            if (dmList != null) {
                for (DeviceModel dm : dmList) {
                    if (currentBox.getBoxCpuId().equals(dm.getBoxCpuId())) {
                        if("15".equals(dm.getDeviceId()) || "06".equals(dm.getDeviceId())){
                            try {
                                Thread.currentThread().sleep(3000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            //向底层发送删除指令
                            RestCmd.getInstance().deanRestOneCmd(dm.getBoxCpuId(), dm.getDeviceId(), dm.getDeviceNumber());
                        }else {
                            try {
                                Thread.currentThread().sleep(3000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            //向底层发送删除指令
                            RestCmd.getInstance().deanRestOneCmd(dm.getBoxCpuId(), dm.getDeviceId(), "00"+dm.getDeviceNumber());//除了id为15和06设备底层删除设备时候指令少1bit需要在deviceNumber前面拼加00
                        }
                    }

                    //本地数据删除
                    if("1C".equals(object.getString("deviceId"))){
                        deviceModelDao.delByDeviceIdNumber(dm.getBoxCpuId(),dm.getDeviceId(),dm.getDeviceNumber());
                    }else {
                        deviceModelDao.del(dm);
                    }

                }
            }
        }

//        //添加时间戳
//        if(StringUtil.isNullOrEmpty(jsonObject.getString("lastHandelTime")+"")){
//            currentBox.setLastHandelTime( DateUtil.getDateLong()+"");
//        } else {
//            currentBox.setLastHandelTime(jsonObject.getString("lastHandelTime"));
//        }
//
//        //更新操作时间
//        boxModelDao.add(currentBox);

//        Log.v(TAG,"操作时间更新成功------"+jsonObject.getString("lastHandelTime"));

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 14 停止设备
    public void doStopDevice(String serverId, JSONObject jsonObject) {

        BoxModel currentBox = boxModelDao.getCurrentBox();
        DeviceModel dm = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(jsonObject.getString("boxCpuId"), jsonObject.getString("deviceId"), jsonObject.getString("deviceNumber"), jsonObject.getString("way"));
        if (dm != null) {
            if (currentBox.getBoxCpuId().equals(dm.getBoxCpuId())) {
                ControlDeviceCmd.getInstance().stopDevice(dm.getBoxCpuId(), dm.getDeviceId(), dm.getDeviceNumber(), dm.getWay());
            }
        }

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type=15 设置新主机名
    public void doSetBoxNewName(String serverId, JSONObject jsonObject) {

        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        String newBoxName = jsonObject.getString("newBoxName");
        if (newBoxName == null || "".equals(newBoxName.trim())) {
            return;
        }

        BoxModel boxModel15 = boxModelDao.getBoxByCpuId(boxCpuId);
        if (boxModel15 != null) {
            boxModel15.setBoxName(newBoxName);
//            //添加时间戳
//            if(StringUtil.isNullOrEmpty(jsonObject.getString("lastHandelTime")+"")){
//                boxModel15.setLastHandelTime( DateUtil.getDateLong()+"");
//            } else {
//                boxModel15.setLastHandelTime(jsonObject.getString("lastHandelTime"));
//            }
            boxModelDao.add(boxModel15);

//            Log.v(TAG,"操作时间更新成功------"+jsonObject.getString("lastHandelTime"));
        }

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type=16 复位全部设备,兼容指定主机删除
    public void doResetAllDevice(String serverId, JSONObject jsonObject) {

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        if (boxCpuId == null || "".equals(boxCpuId.trim())) {
            return;
        }

        deviceModelDao.deleteByBoxCpuId(boxCpuId);
        if (currentBox.getBoxCpuId().equals(boxCpuId)) {
            //发送删除指令
            RestCmd.getInstance().restAllCmd();
        }

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type=22 设置校验时间
    public void doSetCheckTime(String serverId, JSONObject jsonObject) {

        BoxModel currentBox = boxModelDao.getCurrentBox();

        DeviceModel dm22 = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(jsonObject.getString("boxCpuId"), jsonObject.getString("deviceId"), jsonObject.getString("deviceNumber"), jsonObject.getString("way"));

        if (dm22 != null) {
            dm22.setCheckTime(Integer.parseInt(jsonObject.getString("checkTime")));
            deviceModelDao.add(dm22);
        }

        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if (currentBox.getBoxCpuId().equals(boxCpuId)) {
            QueryCmd.getInstance().setDeviceCheckTime(dm22.getBoxCpuId(), dm22.getDeviceId(), dm22.getDeviceNumber(), dm22.getWay(), dm22.getCheckTime());
        }

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }

    }

    //type=23 设置电量监控消息
    public void doSetDevicePower(String serverId, JSONObject jsonObject) {

        JSONArray list23 = jsonObject.getJSONArray("list");
        JSONObject job23;
        DeviceModel dm23;
        for (int i = 0; i < list23.size(); i++) {
            job23 = list23.getJSONObject(i);
            dm23 = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(job23.getString("boxCpuId"), job23.getString("deviceId"), job23.getString("deviceNumber"), job23.getString("way"));
            if (dm23 != null) {
                dm23.setPower(job23.getString("power"));
                dm23.setMonitorState(job23.getString("monitorState"));
                deviceModelDao.add(dm23);
            }
        }

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type=25 设置设备始终布防状态
    public void doSetDeviceAlarmFlag(String serverId, JSONObject jsonObject) {

        JSONArray list = jsonObject.getJSONArray("list");
        if (list == null) {
            return;
        }

        JSONObject job;
        DeviceModel dm25;
        for (int i = 0; i < list.size(); i++) {
            job = list.getJSONObject(i);
            dm25 = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(job.getString("boxCpuId"), job.getString("deviceId"), job.getString("deviceNumber"), job.getString("way"));
            if (dm25 != null) {
                dm25.setAlarmFlag(job.getString("alarmFlag"));
                deviceModelDao.add(dm25);
            }
        }

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type=26 删除房间
    public void doDeleteRoom(String serverId, JSONObject jsonObject) {
        BoxModel currentBox = boxModelDao.getCurrentBox();
        String roomName = jsonObject.getString("roomName");
        if (roomName == null || "".equals(roomName.trim())) {
            return;
        }

        if (deviceModelDao.getDeviceListByRoomName(roomName).size() < 1) {
            //删除房间数据
            roomModelDao.del(roomModelDao.getByName(roomName));
        }

//        //添加时间戳
//        if(StringUtil.isNullOrEmpty(jsonObject.getString("lastHandelTime")+"")){
//            currentBox.setLastHandelTime( DateUtil.getDateLong()+"");
//        } else {
//            currentBox.setLastHandelTime(jsonObject.getString("lastHandelTime"));
//        }
//
//        boxModelDao.add(currentBox);
//        Log.v(TAG,"操作时间更新成功------"+jsonObject.getString("lastHandelTime"));

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type = 27 动作执行失败
    public void doActionFail(String serverId, JSONObject jsonObject) {
        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());
    }

    //type=28 设置系统布防状态
    public void doSetSystemAlarmFlag(String serverId, JSONObject jsonObject) {

        String alarmFlag = jsonObject.getString(GatewaytConstant.SYSTEM_KEY_NAME_ALARM_FLAG);
        if (!"true".equals(alarmFlag) && !"false".equals(alarmFlag)) {
            return;
        }

        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        SystemValueModel svmd = systemValueModelDao.getByName(boxCpuId, GatewaytConstant.SYSTEM_KEY_NAME_ALARM_FLAG);
        svmd.setValue(alarmFlag);
        systemValueModelDao.add(svmd);

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 31 添加情景数据
    public void doAddSceneInfo(String serverId, JSONObject jsonObject) {

        JSONObject dataObj = jsonObject.getJSONObject("data");
        if (dataObj == null) {
            return;
        }

        String sceneName = dataObj.getString("sceneName");
        if (StringUtil.isNullOrEmpty(sceneName)) {
            return;
        }
        //判断情景模式名称是否重复
        SceneModel sceneModel = sceneModelDao.getSceneModelOnly(sceneName);
        if (sceneModel != null) {
            Log.e(TAG, "情景名:" + sceneName + "已存在");
            return;
        }

        //1.添加情景数据
        sceneModel = new SceneModel();
        sceneModel.setBoxCpuId(jsonObject.getString("currentBoxCpuId"));
        sceneModel.setSceneName(dataObj.getString("sceneName"));
        sceneModel.setSceneType(dataObj.getInteger("triggerType"));
        sceneModel.setOpenFlag((dataObj.getString("openFlag") == null) ? "true" : dataObj.getString("openFlag"));
        sceneModel.setIconName(dataObj.getString("sceneIcon") == null ? "" : dataObj.getString("sceneIcon"));
        sceneModel.setCheckModel(dataObj.getString("chooseAll"));
        sceneModel.setCreateTime(System.currentTimeMillis());
        sceneModelDao.add(sceneModel);

        //2.添加条件
        ////A.添加时间条件
        JSONArray timeConditionList = dataObj.getJSONArray("conditionTimeList");
        if (timeConditionList.size() > 1) {
            Log.e(TAG, "时间条件集合数据大于1");
            return;
        }

        if (timeConditionList.size() > 0) {
            JSONObject timeConditionObj = timeConditionList.getJSONObject(0);
            ConditionTimeModel conditionTimeModel = new ConditionTimeModel();
            conditionTimeModel.setSceneName(sceneName);
            conditionTimeModel.setConditionType(0);
            switch (timeConditionObj.getInteger("timeType")) {
                case 0://延时
                    conditionTimeModel.setDelayStartTime(System.currentTimeMillis());
                    conditionTimeModel.setDelayDelayTime(timeConditionObj.getLong("delayTimeMills"));
                    conditionTimeModel.setConditionSubType(0);
                    break;
                case 1://时效
                    conditionTimeModel.setAgingStartTime(timeConditionObj.getLong("agingTimeMillsFrom"));
                    conditionTimeModel.setAgingStopTime(timeConditionObj.getLong("agingTimeMillsTo"));
                    conditionTimeModel.setConditionSubType(1);
                    break;
                case 2://定时
                    conditionTimeModel.setConditionSubType(2);
                    conditionTimeModel.setDimingModelType(0);
                    conditionTimeModel.setHours(timeConditionObj.getInteger("timingHour"));
                    conditionTimeModel.setMinutes(timeConditionObj.getInteger("timingMinute"));
                    conditionTimeModel.setSeconds(timeConditionObj.getInteger("timingSecond"));
                    switch (conditionTimeModel.getDimingModelType()) {
                        case 0://每天
                            break;
                        case 1://每周
                            conditionTimeModel.setWeekDays(timeConditionObj.getString("timingList"));
                            break;
                        case 2://每月
                            conditionTimeModel.setMonthDays(timeConditionObj.getString("timingList"));
                            break;
                        default:
                            Log.e(TAG, "未定义的定时模式");
                            break;
                    }
                    break;
                default:
                    Log.e(TAG, "未定义的时间类型");
                    break;
            }
            conditionTimeModelDao.add(conditionTimeModel);
        }

        ////B.添加状态条件
        JSONArray conditionStateList = dataObj.getJSONArray("conditionStateList");
        Iterator iterator = conditionStateList.iterator();
        JSONObject conditionStateObj = null;
        ConditionStatusModel conditionStatusModel = null;
        while (iterator.hasNext()) {
            conditionStatusModel = new ConditionStatusModel();
            conditionStatusModel.setSceneName(sceneName);
            conditionStatusModel.setConditionType(2);
            conditionStateObj = (JSONObject) iterator.next();
            conditionStatusModel.setConditionSubType(conditionStateObj.getInteger("actionType"));
            conditionStatusModel.setBoxCpuId(conditionStateObj.getString("boxCpuId"));
            conditionStatusModel.setDeviceId(conditionStateObj.getString("deviceId"));
            conditionStatusModel.setDeviceNumber(conditionStateObj.getString("deviceNumber"));
            conditionStatusModel.setWay(conditionStateObj.getString("way") == null ? "01" : conditionStateObj.getString("way"));
            conditionStatusModel.setDeviceName(conditionStateObj.getString("deviceName"));
            conditionStatusModel.setDeviceStatus(conditionStateObj.getString("deviceStatus"));
            conditionStatusModel.setIfAnyone(conditionStateObj.getString("ifAnyone"));
            if("0D".equals(conditionStateObj.getString("deviceId"))){
                if("00".equals(conditionStateObj.getString("deviceStatus"))){
                    conditionStatusModel.setConditionSubType(1);
                }else if ("01".equals(conditionStateObj.getString("deviceStatus"))){
                    conditionStatusModel.setConditionSubType(0);
                }
            }else if ("17".equals(conditionStateObj.getString("deviceId"))){
                if("C4".equals(conditionStateObj.getString("deviceStatus"))){
                    conditionStatusModel.setConditionSubType(1);
                }else if ("C0".equals(conditionStateObj.getString("deviceStatus"))){
                    conditionStatusModel.setConditionSubType(0);
                }

            }else if ("0E".equals(conditionStateObj.getString("deviceId"))){
                if("77".equals(conditionStateObj.getString("deviceStatus"))){
                    conditionStatusModel.setConditionSubType(1);
                }else if ("00".equals(conditionStateObj.getString("deviceStatus"))){
                    conditionStatusModel.setConditionSubType(1);
                }else if ("FF".equals(conditionStateObj.getString("deviceStatus"))){
                    conditionStatusModel.setConditionSubType(0);
                }
            }else {
                if("00".equals(conditionStateObj.getString("deviceStatus"))){
                    conditionStatusModel.setConditionSubType(1);
                }else if ("FF".equals(conditionStateObj.getString("deviceStatus"))){
                    conditionStatusModel.setConditionSubType(0);
                }
            }
            switch (conditionStatusModel.getConditionSubType()) {
                case 2: //调度状态
                    conditionStatusModel.setDimmingValue(conditionStateObj.getString("deviceStatus"));
                    break;
                default:
                    break;
            }
            conditionStatusModelDao.add(conditionStatusModel);
        }

        ////C.添加传感条件
        JSONArray conditionSensingList = dataObj.getJSONArray("conditionSensingList");
        Iterator iterator1 = conditionSensingList.iterator();
        JSONObject conditionSensorObj = null;
        ConditionSensorModel conditionSensorModel = null;
        while (iterator1.hasNext()) {
            conditionSensorObj = (JSONObject) iterator1.next();
            conditionSensorModel = new ConditionSensorModel();
            conditionSensorModel.setSceneName(sceneName);
            conditionSensorModel.setConditionType(1);
            conditionSensorModel.setConditionSubType(conditionSensorObj.getInteger("sensingDeviceType"));
            conditionSensorModel.setBoxCpuId(conditionSensorObj.getString("boxCpuId"));
            conditionSensorModel.setDeviceId(conditionSensorObj.getString("deviceId"));
            conditionSensorModel.setDeviceNumber(conditionSensorObj.getString("deviceNumber"));
            conditionSensorModel.setWay(conditionSensorObj.getString("way") == null ? "01" : conditionSensorObj.getString("way"));
            conditionSensorModel.setDeviceName(conditionSensorObj.getString("deviceName"));
            if (conditionSensorObj.getInteger("sensingDeviceType")!=4){//表示非温湿度时候取检测模型
                conditionSensorModel.setConditionCheckModel(conditionSensorObj.getString("checkModel"));
            }
            switch (conditionSensorModel.getConditionSubType()) {
                case 0: //二氧化碳
                    conditionSensorModel.setCheckCO2Value(conditionSensorObj.getInteger("checkValue"));
                    break;
                case 1: //空气质量
                    conditionSensorModel.setCheckAirValue(conditionSensorObj.getString("checkValue"));
                    break;
                case 2: //PM2.5
                    conditionSensorModel.setCheckPM25Value(conditionSensorObj.getInteger("checkValue"));
                    break;
                case 3: //光照
                    conditionSensorModel.setCheckLightValue(conditionSensorObj.getInteger("checkValue"));
                    break;
                case 4: //温湿度
                    String[] values = conditionSensorObj.getString("checkValue").split("\\|");
                    String [] checkModel=conditionSensorObj.getString("checkModel").split("\\|");
                    if(!"null".equals(values[0])){
                        conditionSensorModel.setCheckTemperatureValue(Integer.parseInt(values[0]));
                        conditionSensorModel.setConditionCheckModel(checkModel[0]);
                    }else{
                        conditionSensorModel.setCheckTemperatureValue(-1314);
                        conditionSensorModel.setConditionCheckModel("-1");
                    }

                    if("null".equals(values[0])){
                        conditionSensorModel.setCheckHumidityValue(Integer.parseInt(values[1]));
                        conditionSensorModel.setConditionCheckModel(checkModel[1]);
                    }else{
                        conditionSensorModel.setCheckHumidityValue(-1314);
                    }


                    break;
                case 5: //风雨传感器

                    break;
                case 6: //报警类设备
                    conditionSensorModel.setCheckAlarmValue(conditionSensorObj.getString("checkValue"));
                    break;
                default:
                    Log.e(TAG, "未定义的传感条件类型");
                    break;
            }
            conditionSensorModelDao.add(conditionSensorModel);
        }

        //3.添加动作
        JSONArray actionList = dataObj.getJSONArray("actionList");
        Iterator iterator2 = actionList.iterator();
        ActionModel actionModel = null;
        JSONObject actionObj = null;
        while (iterator2.hasNext()) {
            actionObj = (JSONObject) iterator2.next();

            actionModel = new ActionModel();
            actionModel.setSceneName(sceneName);
            actionModel.setActionType(actionObj.getInteger("actionType"));
            actionModel.setBoxCpuId(actionObj.getString("boxCpuId"));
            actionModel.setDeviceId(actionObj.getString("deviceId"));
            actionModel.setDeviceNumber(actionObj.getString("deviceNumber"));
            actionModel.setWay(actionObj.getString("way") == null ? "01" : actionObj.getString("way"));
            actionModel.setDeviceName(actionObj.getString("deviceName"));
            actionModel.setDelayActionTime(actionObj.getInteger("delayTime"));
            actionModel.setOrderNumber(Integer.parseInt(actionObj.getString("actionDeviceOrder")));
            switch (actionModel.getActionType()) {
                case 2:
                    String dimmingValue;
                    if (actionObj.getInteger("dimmingValue")==0){
                        dimmingValue="00";
                    }else {
                        dimmingValue="FF";
                    }
                    actionModel.setDimmingValue(dimmingValue);
                    break;
                default:
                    break;
            }
            actionModelDao.add(actionModel);
        }

        //添加家电动作
        JSONArray actionInfraredList = dataObj.getJSONArray("actionInfraredList");
        Iterator iterator3 = actionInfraredList.iterator();
        JSONObject actionInfraredObj = null;
        ActionInfraredModel actionInfraredModel = null;
        while (iterator3.hasNext()) {
            actionInfraredObj = (JSONObject) iterator3.next();

            actionInfraredModel = new ActionInfraredModel();
            actionInfraredModel.setSceneName(sceneName);
            actionInfraredModel.setActionType(actionInfraredObj.getInteger("actionType"));
            actionInfraredModel.setMachineName(actionInfraredObj.getString("machineName"));
            actionInfraredModel.setButtonId(actionInfraredObj.getInteger("buttonId"));
            actionInfraredModel.setButtonName(actionInfraredObj.getString("buttonName"));
            actionInfraredModel.setDelayActionTime(actionInfraredObj.getInteger("delayTime"));
            actionInfraredModel.setOrderNumber(actionInfraredObj.getInteger("actionInfraredOrder"));
            actionInfraredModelDao.add(actionInfraredModel);
        }

        SceneServer.getInstance().setSceneOpenFlag(true);
        SceneServer.getInstance().loadSceneList();


        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 32 删除情景数据
    public void doDelSceneInfo(String serverId, JSONObject jsonObject) {

        String sceneName = jsonObject.getString("sceneName");
        if (StringUtil.isNullOrEmpty(sceneName)) {
            return;
        }

        //服务中删除
        SceneServer.getInstance().delScene(sceneName);
        //删除存储的数据
        sceneModelDao.delSceneAllData(sceneName);
        actionInfraredModelDao.del(sceneName);
        //重新加载情景
//        SceneServer.getInstance().loadSensorList();
//        SceneServer.getInstance().loadTimeList();
//        SceneServer.getInstance().loadStatusList();
//        SceneServer.getInstance().loadPasstiveSceneList();
        SceneServer.getInstance().loadSceneList();
        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 33 手动触发情景
    public void doManualOpenScene(String serverId, JSONObject jsonObject) {
        String sceneName = jsonObject.getString("sceneName");

        if (StringUtil.isNullOrEmpty(sceneName)) {
            return;
        }

        SceneServer.getInstance().checkPasstiveScene(sceneName);

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 34 打开/关闭被动情景
    public void doSetPasstiveScene(String serverId, JSONObject jsonObject) {
        String sceneName = jsonObject.getString("sceneName");
        String openFlag = jsonObject.getString("openFlag");
        if (StringUtil.isNullOrEmpty(sceneName, openFlag)) {
            return;
        }

        if (!"true".equals(openFlag) && !"false".equals(openFlag)) {
            return;
        }

        SceneModel sceneModel = sceneModelDao.getSceneModelOnly(sceneName);
        if (sceneModel == null) {
            return;
        }

        sceneModel.setOpenFlag(openFlag);
        sceneModelDao.add(sceneModel);

        SceneServer.getInstance().loadSceneList();
//        SceneServer.getInstance().loadSensorList();
//        SceneServer.getInstance().loadTimeList();
//        SceneServer.getInstance().loadStatusList();

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 35 加音量
    public void doAddSounds(String serverId, JSONObject jsonObject) {
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if (boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)) {
            VolumeControl.getInstance().addSounds();
        }

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 36 减音量
    public void doDelSounds(String serverId, JSONObject jsonObject) {
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if (boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)) {
            VolumeControl.getInstance().delSounds();
        }

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 37 静音
    public void doNoSounds(String serverId, JSONObject jsonObject) {
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if (boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)) {
            VolumeControl.getInstance().setNoSounds();
        }

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 38 静音恢复
    public void doNoSoundsReset(String serverId, JSONObject jsonObject) {
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if (boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)) {
            VolumeControl.getInstance().setNoSoundsReset();
        }

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 39 控制向上
    public void doMoveUp(String serverId, JSONObject jsonObject) {
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if (boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)) {
            MoveControl.getInstance().moveUp();
        }

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 40 控制向下
    public void doMoveDown(String serverId, JSONObject jsonObject) {
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if (boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)) {
            MoveControl.getInstance().moveDown();
        }

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 41 控制向左
    public void doMoveLeft(String serverId, JSONObject jsonObject) {
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if (boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)) {
            MoveControl.getInstance().moveLeft();
        }

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 42 控制向右
    public void doMoveRight(String serverId, JSONObject jsonObject) {
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if (boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)) {
            MoveControl.getInstance().moveRight();
        }

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 43 返回主页
    public void doBackHome(String serverId, JSONObject jsonObject) {
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if (boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)) {
            PageControl.getInstance().backHome();
        }

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 44 弹出系统菜单
    public void doPopMenu(String serverId, JSONObject jsonObject) {
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if (boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)) {
            PageControl.getInstance().popMenu();
        }

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 45 返回上页
    public void doBackPre(String serverId, JSONObject jsonObject) {
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if (boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)) {
            PageControl.getInstance().backPre();
        }

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 46 OK确认按钮
    public void doConfirm(String serverId, JSONObject jsonObject) {
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if (boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)) {
            PageControl.getInstance().confirm();
        }

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 47 修改用户信息
    public void doUpdateUserInfo(String serverId, JSONObject jsonObject) {

        String userName = jsonObject.getString("userName");
        if (StringUtil.isNullOrEmpty(userName)) {
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if (userModel == null) {
            return;
        }

        boolean updateFlag = false;

        String phone = jsonObject.getString("phone");
        if (phone == null || "".equals(phone.trim())) {

        } else {
            userModel.setPhone(phone);
            updateFlag = true;
        }

        String email = jsonObject.getString("email");
        if (email == null || "".equals(email.trim())) {

        } else {
            userModel.setEmail(email);
            updateFlag = true;
        }

        String idCard = jsonObject.getString("idCard");
        if (idCard == null || "".equals(idCard.trim())) {

        } else {
            userModel.setIdCard(idCard);
            updateFlag = true;
        }

        String logo = jsonObject.getString("logo");
        if (logo == null || "".equals(logo.trim())) {

        } else {
            userModel.setLogo(logo);
            updateFlag = true;
        }

        String nickName = jsonObject.getString("nickName");
        if (nickName == null || "".equals(nickName.trim())) {

        } else {
            userModel.setNickName(nickName);
            updateFlag = true;
        }

        String password = jsonObject.getString("password");
        if (password == null || "".equals(password.trim())) {

        } else {
            userModel.setPassword(new JackMd5().enCription(password));
            updateFlag = true;
        }

        if (!updateFlag) {
            return;
        }

        userModelDao.add(userModel);
        userInfoUpdate();

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //发送用户信息更新广播
    public void userInfoUpdate() {
        UserModel userModel = userModelDao.getUserFirst();
        if (userModel != null) {
            if (userModel.getUserName() != null) {
                Intent intent = new Intent();
                intent.setAction(LauncherMessageReceiver.ACTION_USER_UPDATE_INFO);
                intent.putExtra("userName", userModel.getNickName());
                intent.putExtra("userLogo", userModel.getLogo());
                context.sendBroadcast(intent);
            }
        }
    }

    // type = 55    //发送按钮控制指令,只有手机连接服务器的时候才会转发指令到指定机顶盒
    public void doSendControl(String serverId, JSONObject jsonObject) {
        String userName = jsonObject.getString("userName");

        String isStudyType = jsonObject.getString("isStudyType");
        if (StringUtil.isNullOrEmpty(userName, isStudyType)) {
            Log.e(getClass().getName(), "缺少参数userName或者isStudyType");
            return;
        }

        String bindBoxCpuId = jsonObject.getString("bindBoxCpuId");
        String bindDeviceId = jsonObject.getString("bindDeviceId");
        String bindDeviceNumber = jsonObject.getString("bindDeviceNumber");
        String bindWay = jsonObject.getString("bindWay");

        UserModel userModel = userModelDao.getByName(userName);
        if (userModel == null) {
            return;
        }

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if (!currentBox.getBoxCpuId().equals(boxCpuId)) {
            return;
        }

        long controlKey = jsonObject.getLong("controlKey");
        int deviceType = jsonObject.getInteger("machineTypeId");
        String controlDataStr = jsonObject.getString("controlData");

        //如果是空调类,在没有指令的时候，手动生成
        if (5 == deviceType && (null == controlDataStr || "".equals(controlDataStr.trim()))) {
            JSONObject controlObj = jsonObject.getJSONObject("controlObj");
            if (controlObj == null) {
                Log.w(TAG, "用户传输信息数据错误!");
                return;
            }
            String machineName = controlObj.getString("machineName");
            int type = controlObj.getInteger("type");
            String modelName = controlObj.getString("modelName");
            int power = controlObj.getInteger("power");
            int mode = controlObj.getInteger("mode");
            int temperature = controlObj.getInteger("temperature");
            int windSpeed = controlObj.getInteger("windSpeed");
            int windDirection = controlObj.getInteger("windDirection");

            //计算生成指令码
            int[] array = new int[]{power, mode, temperature, windSpeed, windDirection};
            Remote_obj remote_obj = new Remote_obj();
            String[] result = remote_obj.Creat_air_code(Integer.parseInt(modelName), type, array);
            controlDataStr = result[0];
        } else {
            if (null == controlDataStr || "".equals(controlDataStr.trim())) {
                return;
            }
        }

        byte[] controlData = HexTool.HexToByteArr(controlDataStr);

        if (!StringUtil.isNullOrEmpty(bindBoxCpuId, bindDeviceId, bindDeviceNumber, bindWay)) {
            if (Boolean.parseBoolean(isStudyType)) {
                InfraredControlCmd.getInstance().controlCmd(bindBoxCpuId, bindDeviceId, bindDeviceNumber, bindWay, controlData, controlKey + "");
            } else {
                int length = controlData.length + 2;
                String lengthStr;
                if (length > 255) {
                    lengthStr = Integer.toHexString(length);
                } else {
                    lengthStr = "00" + Integer.toHexString(length);
                }

                InfraredControlCmd.getInstance().controlCmd2(bindBoxCpuId, bindDeviceId, bindDeviceNumber, bindWay, controlData, controlKey + "", HexTool.HexToByteArr(lengthStr), (byte) deviceType);
            }
        } else {
            int deviceId = 0x00;

            ControlMessage controlMessage = new ControlMessage();
            controlMessage.setDeviceType((byte) deviceType);
            controlMessage.setDeviceId((byte) deviceId);
            controlMessage.setControlData(controlData);
            controlMessage.setUserName(userModel.getUserName());
            controlMessage.setControlKey(controlKey);
            int length = controlData.length + 2;
            String lengthStr;
            if (length > 255) {
                lengthStr = Integer.toHexString(length);
            } else {
                lengthStr = "00" + Integer.toHexString(length);
            }
            controlMessage.setLength(HexTool.HexToByteArr(lengthStr));
            InfraredServer.getInstance().send(controlMessage);
        }
    }

    // type = 58    //添加家电设备
    public void doAddUserMachine(String serverId, JSONObject jsonObject) {

        String userName = jsonObject.getString("userName");
        if (StringUtil.isNullOrEmpty(userName)) {
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if (userModel == null) {
            return;
        }

        String currentBoxCpuId = jsonObject.getString("currentBoxCpuId");
        int machineTypeId = jsonObject.getInteger("machineTypeId");
        String brandName = jsonObject.getString("brandName");
        String modelName = jsonObject.getString("modelName");
        String roomName = jsonObject.getString("roomName");
        int addType = jsonObject.containsKey("addType") ? jsonObject.getInteger("addType") : 3;
        String machineName = jsonObject.getString("machineName");

        String bindBoxCpuId = jsonObject.getString("bindBoxCpuId");
        String bindDeviceId = jsonObject.getString("bindDeviceId");
        String bindDeviceNumber = jsonObject.getString("bindDeviceNumber");
        String bindWay = jsonObject.getString("bindWay");
        String machineStatus = jsonObject.getString("applianceStatus");
        if (machineTypeId == 11) {
            modelName = "自定义型号";
            brandName = "自动以品牌";
        } else {
            if (modelName == null || "".equals(modelName.trim())) {
                Log.w(TAG, "型号名不能为空");
                return;
            }
        }


        Brand brand = brandDao.get(brandName);
        if (brand == null) {
            if (machineTypeId == 11) {
                brand = new Brand();
                brand.setBrandCh(brandName);
                brand.setBrandEn(brandName);
                brand.setNote(brandName);
                brandDao.add(brand);
                brand = brandDao.get(brandName);
            } else {
                Log.w(TAG, "品牌不存在!");
                return;
            }
        }

        BrandModel brandModel = brandModelDao.get(machineTypeId, brand.getBrandId(), modelName);
        if (brandModel == null) {
            brandModel = new BrandModel();
            brandModel.setMachineTypeId(machineTypeId);
            brandModel.setBrandId(brand.getBrandId());
            brandModel.setModelName(modelName);
            brandModel.setModelType("user");
            brandModelDao.add(brandModel);
            brandModel = brandModelDao.get(machineTypeId, brand.getBrandId(), modelName);
        }

        UserMachine userMachine = userMachineDao.get(userModel.getUserName(), machineName);
        if (userMachine == null) {
            userMachine = new UserMachine();
            userMachine.setUserName(userModel.getUserName());
            userMachine.setMachineName(machineName);
            userMachine.setRoomName(roomName);
            userMachine.setAddType(addType);
            userMachine.setBrandModelId(brandModel.getBrandModelId());
            userMachine.setBoxCpuId(currentBoxCpuId);
            userMachine.setBindBoxCpuId(bindBoxCpuId);
            userMachine.setBindDeviceNumber(bindDeviceNumber);
            userMachine.setBindDeviceId(bindDeviceId);
            userMachine.setBindWay(bindWay);
            userMachine.setMachineTypeId(machineTypeId);
            userMachine.setStatus(machineStatus);
            userMachineDao.add(userMachine);
        } else {
            Log.w(TAG, "家电名已存在");
        }

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    // type = 59    //删除家电设备
    public void doDelUserMachine(String serverId, JSONObject jsonObject) {

        String userName = jsonObject.getString("userName");
        if (StringUtil.isNullOrEmpty(userName)) {
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if (userModel == null) {
            return;
        }

        if (jsonObject.containsKey("machineName")) {
            String machineName = jsonObject.getString("machineName");
            UserMachine userMachine = userMachineDao.get(userModel.getUserName(), machineName);
            if (userMachine != null) {

                //删除设备按钮
                List<UserMachineButton> buttonList = userMachineButtonDao.getList(machineName);
                for (UserMachineButton umb : buttonList) {
                    userMachineButtonDao.del(umb);
                }
                //删除设备
                userMachineDao.del(userMachine);
            } else {
                Log.w(TAG, "家电不存在!");
            }

            //发送所有当前手机
            UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

            if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
                jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
                //发送其他机顶盒
                BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
            }
        }
    }

    // type = 60    //添加家电按钮
    public void doAddMachineButton(String serverId, JSONObject jsonObject) {

        String userName = jsonObject.getString("userName");
        if (StringUtil.isNullOrEmpty(userName)) {
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if (userModel == null) {
            return;
        }

        if (jsonObject.containsKey("machineName") && jsonObject.containsKey("buttonId")) {
            String machineName = jsonObject.getString("machineName");
            int buttonId = jsonObject.getInteger("buttonId");
            UserMachineButton userMachineButton = userMachineButtonDao.get(machineName, buttonId);
            if (userMachineButton == null) {
                userMachineButton = new UserMachineButton();
                userMachineButton.setMachineName(machineName);
                userMachineButton.setButtonId(buttonId);
                userMachineButton.setButtonName(jsonObject.getString("buttonName"));
                userMachineButton.setCode(jsonObject.getString("code"));
                userMachineButton.setStudyFlag(jsonObject.getString("studyFlag"));
                userMachineButtonDao.add(userMachineButton);
            } else {
                userMachineButton.setButtonName(jsonObject.getString("buttonName"));
                userMachineButton.setCode(jsonObject.getString("code"));
                userMachineButton.setStudyFlag(jsonObject.getString("studyFlag"));
                userMachineButtonDao.add(userMachineButton);
            }

            //发送所有当前手机
            UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

            if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
                jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
                //发送其他机顶盒
                BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
            }
        }
    }

    // type = 61 删除家电按钮
    public void doDelMachineButton(String serverId, JSONObject jsonObject) {

        String userName = jsonObject.getString("userName");
        if (StringUtil.isNullOrEmpty(userName)) {
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if (userModel == null) {
            return;
        }

        if (jsonObject.containsKey("machineName") && jsonObject.containsKey("buttonId")) {
            String machineName = jsonObject.getString("machineName");
            int buttonId = jsonObject.getInteger("buttonId");

            UserMachineButton userMachineButton = userMachineButtonDao.get(machineName, buttonId);
            if (userMachineButton != null) {
                userMachineButtonDao.del(userMachineButton);

                //发送所有当前手机
                UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

                if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
                    jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
                    //发送其他机顶盒
                    BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
                }
            } else {
                Log.w(TAG, "该家电按钮不存在!");
            }
        }
    }

    //type = 62 红外控制结果反馈
    public void doSendControlResult(String serverId, JSONObject jsonObject) {
        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());
    }

    //type = 65 家电状态同步消息
    public void doSynUserMachineStatus(String serverId, JSONObject jsonObject) {

        String userName = jsonObject.getString("userName");
        if (StringUtil.isNullOrEmpty(userName)) {
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if (userModel == null) {
            return;
        }

        if (jsonObject.containsKey("machineName") && jsonObject.containsKey("status")) {

            String machineName = jsonObject.getString("machineName");
            String status = jsonObject.getString("status");

            UserMachine userMachine = userMachineDao.get(userName, machineName);
            if (userMachine != null) {
                userMachine.setStatus(status);
                userMachineDao.add(userMachine);
            }

            //发送所有当前手机
            UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

            if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
                jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
                //发送其他机顶盒
                BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
            }
        } else {
            Log.w(TAG, "机顶盒传输信息错误.");
            return;
        }
    }

    //type = 66 解绑机顶盒
    public void doUnbindBox(String serverId, JSONObject jsonObject) {
        String boxCpuId = jsonObject.getString("boxCpuId");
//        if (StringUtil.isNullOrEmpty(boxCpuId)) {
//            boxCpuId = jsonObject.getString("currentBoxCpuId");
//        }

        BoxModel currentBox = boxModelDao.getCurrentBox();

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }

        if (currentBox.getBoxCpuId().equals(boxCpuId)) {

            //发送删除指令
            RestCmd.getInstance().restAllCmd();

            //删除服务
            SceneServer.getInstance().stop();
            UserServer.getInstance().stop();
            BoxServer.getInstance().stop();
            RemoteClient.getInstance().stop();
            for (BoxClient boxClient : BoxClientManager.getAll()) {
                if (boxClient != null) {
                    boxClient.stop();
                }
            }

            //删除网关数据
            deviceModelDao.delAll();
            deviceModelHistoryDao.delAll();
            deviceDayPowerConsumptionDao.delAll();
            deviceMonthPowerConsumptionDao.delAll();

            //删除家电数据
            userMachineDao.delAll();
            userMachineButtonDao.delAll();

            //删除情景数据

            sceneModelDao.delAll();
            actionModelDao.delAll();
            actionInfraredModelDao.delAll();
            conditionTimeModelDao.delAll();
            conditionSensorModelDao.delAll();
            conditionStatusModelDao.delAll();

            //删除房间数据
            roomModelDao.delAll();

            //删除系统设置数据
            systemValueModelDao.delAll();

            //删除手机连接
            userLoginDao.delAll();

            //删除box连接
            boxPhoneDao.delAll();
            boxLoginDao.delAll();

            //删除用户数据
            userModelDao.delAll();

            //删除机顶盒信息
            boxModelDao.delAll();

            EventUnbindBox event = new EventUnbindBox();
            event.setRestartFlag(true);
            event.setBoxCpuId(boxCpuId);
            EventBus.getDefault().post(event);

            //删除数据库问卷，重启中重新生成
            File file = new File("/data/data/" + context.getPackageName() + "/databases/smartHomeLauncher.db");
            if (file.exists()) {
                file.delete();
            }

            //机顶盒重启
            Tools.restartSystem(context);
        } else {

            //删除机顶盒连接
            for (BoxClient boxClient : BoxClientManager.getAll()) {
                if (boxClient.getBoxCpuId().equals(boxCpuId)) {
                    boxClient.stop();
                }
            }
            BoxLogin boxLogin = boxLoginDao.getBoxLoginByBoxCpuId(boxCpuId);
            if (boxLogin != null) {
                BoxServer.getInstance().refuseClient(boxLogin.getClientId(), "bye-bye");
            }

            //删除网关数据
            deviceModelDao.delBy("boxCpuId", boxCpuId);
            deviceModelHistoryDao.delBy("boxCpuId", boxCpuId);
            deviceDayPowerConsumptionDao.delBy("boxCpuId", boxCpuId);
            deviceMonthPowerConsumptionDao.delBy("boxCpuId", boxCpuId);

            //删除家电数据
            for (UserMachine um : userMachineDao.getAll()) {
                if (um.getBoxCpuId().equals(boxCpuId)) {
                    userMachineButtonDao.del(um.getMachineName());
                    actionInfraredModelDao.delBy("machineName", um.getMachineName());
                    userMachineDao.del(um);
                }
            }

            //删除情景数据
            sceneModelDao.delBy("boxCpuId", boxCpuId);
            actionModelDao.delBy("boxCpuId", boxCpuId);
            conditionTimeModelDao.delBy("boxCpuId", boxCpuId);
            conditionSensorModelDao.delBy("boxCpuId", boxCpuId);
            conditionStatusModelDao.delBy("boxCpuId", boxCpuId);
            SceneServer.getInstance().loadSceneList();

            //删除系统设置数据
            systemValueModelDao.delBy("boxCpuId", boxCpuId);

            //删除box连接
            boxLoginDao.delBy("boxCpuId", boxCpuId);


            //删除机顶盒信息
            boxModelDao.delBy("boxCpuId", boxCpuId);


            EventUnbindBox event = new EventUnbindBox();
            event.setRestartFlag(false);
            event.setBoxCpuId(boxCpuId);
            EventBus.getDefault().post(event);

//            //删除数据库问卷，重启中重新生成
//            File file = new File("/data/data/" + context.getPackageName() + "/databases/smartHomeLauncher.db");
//            if (file.exists()) {
//                file.delete();
//            }
//            Log.v(TAG,"-------------R即将重启------------");
//            Tools.restartSystem(context);
        }
    }

    //type = 71 普通开关绑定情景
    public void doBindScene(String clientId, JSONObject jsonObject) {
        String boxCpuId = jsonObject.getString("boxCpuId");
        if (StringUtil.isNullOrEmpty(boxCpuId)) {
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        JSONObject dataObj = jsonObject.getJSONObject("data");
        if (dataObj == null) {
            return;
        }

        String sceneName = dataObj.getString("sceneName");
        if (StringUtil.isNullOrEmpty(sceneName)) {
            return;
        }

        //1.绑定之前把该情景绑定过此按键的清除绑定的按键
        SceneModel oldSceneModel = sceneModelDao.getSceneModelByDeviceNumberAndSceneKey(dataObj.getString("deviceNumber"),dataObj.getString("sceneBindKey"));
        if (oldSceneModel!=null) {
            oldSceneModel.setDeviceNumber("00");
            oldSceneModel.setSceneBindKey("00");
            sceneModelDao.add(oldSceneModel);
        }
        //2.情景绑定按键过程
        SceneModel sceneModel = sceneModelDao.getSceneModelOnly(sceneName);
        if (sceneModel != null) {
            sceneModel.setSceneBindKey(dataObj.getString("sceneBindKey"));
            sceneModel.setDeviceNumber(dataObj.getString("deviceNumber"));
            sceneModelDao.add(sceneModel);
            jsonObject.put("bindSceneFlag", true);
        } else {

            jsonObject.put("bindSceneFlag", false);
        }

        SceneServer.getInstance().loadPasstiveSceneList();

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }

    }

    //type = 72 添加/修改 用户摄像头账号密码
    public void doSetCameraInfo(String serverId, JSONObject jsonObject) {

        String userName = jsonObject.getString("userName");
        String cameraLoginName = jsonObject.getString("cameraLoginName");
        String cameraPassword = jsonObject.getString("cameraPassword");

        if (StringUtil.isNullOrEmpty(userName, cameraLoginName, cameraPassword)) {
            LoggerManager.getInstance().getiLogger().error(getClass(), "基本参数错误!");
            return;
        }

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String currentUserName = currentBox.getUserName();
        if (!userName.endsWith(currentUserName)) {
            LoggerManager.getInstance().getiLogger().error(getClass(), "用户消息篡位!");
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if (userModel == null) {
            LoggerManager.getInstance().getiLogger().error(getClass(), "用户信息不存在!");
            return;
        }

        userModel.setCameraLoginName(cameraLoginName);
        userModel.setCameraPassword(cameraPassword);
        userModelDao.add(userModel);

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }
    }

    //type = 75 普通开关触发
    public void doSceneKeyDown(String clientId, JSONObject jsonObject) {
        String currentBoxCpuId = jsonObject.getString("currentBoxCpuId");
        JSONObject deviceModelData = jsonObject.getJSONObject("list");
        String deviceNumber = deviceModelData.getString("deviceNumber");
        String sceneBindKey = deviceModelData.getString("deviceStatus");//deviceStatus 也就是绑定的按键标识

        SceneModel sceneModel = sceneModelDao.getSceneModelByDeviceNumberAndSceneKey(deviceNumber, sceneBindKey);

        if (sceneModel != null || "".equals(sceneModel)) {
            String sceneName = sceneModel.getSceneName();
            SceneServer.getInstance().checkPasstiveScene(sceneName);//根据情景名
        }

        if ("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))) {
            jsonObject.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
        }

    }

    //type = 74 设置设备进度值
    public void doSetProcessValue(String serverId, JSONObject jobj) {
        DeviceModel deviceModel = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(jobj.getString("boxCpuId"), jobj.getString("deviceId"), jobj.getString("deviceNumber"), jobj.getString("way"));
        if (deviceModel != null) {
            deviceModel.setProcessValue(jobj.getIntValue("processValue"));
            deviceModelDao.add(deviceModel);
        }

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jobj.toJSONString());

        if ("false".equals(jobj.getString(MsgConstant.HEAD_IS_REPLY))) {
            jobj.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jobj.toJSONString());
        }
    }

    //type = 335 //机顶盒上线
    public void doSetBoxOnline(String serverId, JSONObject jobj) {

        BoxModel boxModel = boxModelDao.getBoxByCpuId(jobj.getString("boxCpuId"));
        if (boxModel != null) {
            boxModel.setStatus("online");
            boxModelDao.add(boxModel);
        }

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jobj.toJSONString());

        if ("false".equals(jobj.getString(MsgConstant.HEAD_IS_REPLY))) {
            jobj.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jobj.toJSONString());
        }
    }

    //type = 336 //机顶盒下线
    public void doSetBoxOffline(String serverId, JSONObject jobj) {

        BoxModel boxModel = boxModelDao.getBoxByCpuId(jobj.getString("boxCpuId"));
        if (boxModel != null) {
            boxModel.setStatus("offline");
            boxModelDao.add(boxModel);
        }

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jobj.toJSONString());

        if ("false".equals(jobj.getString(MsgConstant.HEAD_IS_REPLY))) {
            jobj.put(MsgConstant.HEAD_IS_REPLY, "true");
            //发送其他机顶盒
            BoxServer.getInstance().sendAllBoxMessage(jobj.toJSONString());
        }
    }

    //type = 400 服务器下发更新用户密码
    public void doServerUpdateUserPassword(String serverId, JSONObject jsonObject) {
        String newPassword = jsonObject.getString("newPassword");
        UserModel userModel = userModelDao.getUserFirst();
        userModel.setPassword(newPassword);
        userModelDao.add(userModel);
    }

    public void preOnMessage(String serverId, String message) {
        if (message == null) {
            return;
        }
        JSONObject jobj = null;
        try {
            jobj = JSON.parseObject(message.toString());
        } catch (Exception e) {
            Log.d(TAG, "不是json消息:" + e.getMessage());
        }

        if (jobj == null) {
            return;
        }

        BoxModel currentBox = boxModelDao.getCurrentBox();

        //二次处理消息
        //判断消息中没有MSGID属性
        if (jobj.containsKey(MsgConstant.HEAD_MESSAGE_ID)) {
            //如果有的话，说明已经处理过了
            String msgId = jobj.getString(MsgConstant.HEAD_MESSAGE_ID);
            if (MessageIdManager.contansMsgId(msgId)) {
                return;
            }
        } else {
            String msgId = boxModelDao.getCurrentBox().getBoxCpuId() + "|" + System.currentTimeMillis();
            jobj.put(MsgConstant.HEAD_MESSAGE_ID, msgId);
            MessageIdManager.addMsgId(msgId);
        }

        if (!jobj.containsKey(MsgConstant.HEAD_IS_REPLY)) {
            jobj.put(MsgConstant.HEAD_IS_REPLY, "false");
        }

        int type = jobj.getIntValue("type");
        switch (type) {
            case 2:
            case 7:
            case 13:
            case 15:
            case 6:
                EventBus.getDefault().post(Constants.ACTION_NOTIFY_MAIN_ACTIVITY);
                break;
            case 47:
                UserServer.getInstance().userInfoUpdate();

                break;
        }

        switch (type) {
            case 2:
                doBoxMindAdd(serverId, jobj);
                break;
            case 3:
                doOpenDevice(serverId, jobj);
                break;
            case 4:
                doCloseDevice(serverId, jobj);
                break;
            case 5:
                doDemingDevice(serverId, jobj);
                break;
            case 6:
                doBoxQueryDevice(serverId, jobj);
                break;
            case 7:
                doDeviceBindRoom(serverId, jobj);
                break;
            case 8:
                doOpenAllDevices(serverId, jobj);
                break;
            case 9:
                doCloseAllDevices(serverId, jobj);
                break;
            case 10:
                doAddOneDevice(serverId, jobj);
                break;
            case 13:
                doDeleteDevice(serverId, jobj);
                break;
            case 14:
                doStopDevice(serverId, jobj);
                break;
            case 15:
                doSetBoxNewName(serverId, jobj);
                break;
            case 16:
                doResetAllDevice(serverId, jobj);
                break;
            case 22:
                doSetCheckTime(serverId, jobj);
                break;
            case 23:
                doSetDevicePower(serverId, jobj);
                break;
            case 25:
                doSetDeviceAlarmFlag(serverId, jobj);
                break;
            case 26:
                doDeleteRoom(serverId, jobj);
                break;
            case 27:
                doActionFail(serverId, jobj);
                break;
            case 28:
                doSetSystemAlarmFlag(serverId, jobj);
                break;
            case 31:
                doAddSceneInfo(serverId, jobj);
                break;
            case 32:
                doDelSceneInfo(serverId, jobj);
                break;
            case 33:
                doManualOpenScene(serverId, jobj);
                break;
            case 34:
                doSetPasstiveScene(serverId, jobj);
                break;
            case 35:
                doAddSounds(serverId, jobj);
                break;
            case 36:
                doDelSounds(serverId, jobj);
                break;
            case 37:
                doNoSounds(serverId, jobj);
                break;
            case 38:
                doNoSoundsReset(serverId, jobj);
                break;
            case 39:
                doMoveUp(serverId, jobj);
                break;
            case 40:
                doMoveDown(serverId, jobj);
                break;
            case 41:
                doMoveLeft(serverId, jobj);
                break;
            case 42:
                doMoveRight(serverId, jobj);
                break;
            case 43:
                doBackHome(serverId, jobj);
                break;
            case 44:
                doPopMenu(serverId, jobj);
                break;
            case 45:
                doBackPre(serverId, jobj);
                break;
            case 46:
                doConfirm(serverId, jobj);
                break;
            case 47:
                doUpdateUserInfo(serverId, jobj);
                break;
            case 55:
                doSendControl(serverId, jobj);
                break;
            case 58:
                doAddUserMachine(serverId, jobj);
                break;
            case 59:
                doDelUserMachine(serverId, jobj);
                break;
            case 60:
                doAddMachineButton(serverId, jobj);
                break;
            case 61:
                doDelMachineButton(serverId, jobj);
                break;
            case 62:
                doSendControlResult(serverId, jobj);
                break;
            case 65:
                doSynUserMachineStatus(serverId, jobj);
                break;
            case 66:
                doUnbindBox(serverId, jobj);
                break;
            case 71:  //按键绑定情景
                doBindScene(serverId, jobj);
                break;
            case 72:
                doSetCameraInfo(serverId, jobj);
                break;
            case 74:
                doSetProcessValue(serverId, jobj);
                break;
            case 75:    //按键绑定情景按键触发
                doSceneKeyDown(serverId, jobj);
                break;
            case 333: //自动登录反馈
                RemoteClient.getInstance().remoteloginRepley(jobj);
                break;
            case 335:
                doSetBoxOnline(serverId, jobj);
                break;
            case 336:
                doSetBoxOffline(serverId, jobj);
                break;
            case 400:
                doServerUpdateUserPassword(serverId, jobj);
            default:
                //
        }
    }

    @Override
    public void onConnect(String serverId) {
        remoteLogin();
        Log.v(TAG, "主机客户端连接上来了------------" + serverId);
        BoxModel boxModel = boxModelDao.getCurrentBox();
        boxLoginDao.delAll();
        BoxLogin boxLogin = new BoxLogin();
        boxLogin.setBoxCpuId(boxModel.getBoxCpuId());
        boxLogin.setClientId(serverId);

        BoxLogin boxLogin1 = boxLoginDao.getBoxLoginByBoxCpuId(boxModel.getBoxCpuId());
        if (boxLogin1 == null || "".equals(boxLogin1)) {
            boxLoginDao.add(boxLogin);//客户端上线时存储boxLogin信息
        }


    }

    @Override
    public void onDisconnect(String serverId) {
        setLoginFlag(false);
    }

    @Override
    public void onMessage(String serverId, String message) {
        preOnMessage(serverId, message);
    }
}
